1

我有一个对象列表

List<Flywheel> parts1 = new List<Flywheel>();

我想提取其中一个属性的数组。

 parts1 = parts.DistinctBy(Flywheel => Flywheel.FW_DMF_or_Solid).OrderBy(Flywheel => Flywheel.FW_DMF_or_Solid).ToList();

 string[] mydata = ((IEnumerable)parts1).Cast<Flywheel>()
                              .Select(x => x.ToString())
                              .ToArray();

DistinctBy() 的代码

public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
    {
        HashSet<TKey> seenKeys = new HashSet<TKey>();
        foreach (TSource element in source)
        {
            if (seenKeys.Add(keySelector(element)))
            {
                yield return element;
            }
        }
    }

我在代码中得到的是一个字符串数组,每个字符串都是“XXX.Flywheels.Flywheel”,但我需要获取实际值。

4

3 回答 3

2

这应该有效:

List<Flywheel> parts1 = new List<Flywheel>();
var mydata = parts1.Select(x => x.FW_DMF_or_Solid).OrderBy(x => x).Distinct().ToArray();
于 2013-10-31T13:34:07.113 回答
1

您的ToString()操作员正在输出“XXX.Flywheels.Flywheel”。你需要

string[] mydata = ((IEnumerable)parts1).Cast<Flywheel>()
                          .Select(x => x.FW_DMF_or_Solid.ToString())
                          .ToArray();

此外,您应该能够将您的DistinctBy代码替换为

public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
    return source.GroupBy(x => keySelector(x)).Select(g => g.First());
}
于 2013-10-31T13:38:32.230 回答
0
string[] arrayOfSingleProperty = 
         listOfObjects
        .Select(o => o.FW_DMF_or_Solid)
        .OrderBy(o =>o)
        .Distinct()
        .ToArray();
于 2013-10-31T13:35:59.407 回答