我有一个对象列表
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” 但我需要得到实际值。
答案 0 :(得分:2)
这应该有效:
List<Flywheel> parts1 = new List<Flywheel>();
var mydata = parts1.Select(x => x.FW_DMF_or_Solid).OrderBy(x => x).Distinct().ToArray();
答案 1 :(得分: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());
}
答案 2 :(得分:0)
string[] arrayOfSingleProperty =
listOfObjects
.Select(o => o.FW_DMF_or_Solid)
.OrderBy(o =>o)
.Distinct()
.ToArray();