[英]How to get Array of one property from List of objects?
I have a List of Objects 我有一个对象列表
List<Flywheel> parts1 = new List<Flywheel>();
i want to extract an array of one of the properties. 我想提取其中一个属性的数组。
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();
the code for DistinctBy() 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;
}
}
}
what i get in my code is a array of string thart each of them is "XXX.Flywheels.Flywheel" but i need to get the actual values. 我在我的代码中得到的是一个字符串数组thart每个都是“XXX.Flywheels.Flywheel”但我需要得到实际值。
This should work: 这应该工作:
List<Flywheel> parts1 = new List<Flywheel>();
var mydata = parts1.Select(x => x.FW_DMF_or_Solid).OrderBy(x => x).Distinct().ToArray();
Your ToString()
operator is outputting "XXX.Flywheels.Flywheel". 您的
ToString()
运算符正在输出“XXX.Flywheels.Flywheel”。 You need 你需要
string[] mydata = ((IEnumerable)parts1).Cast<Flywheel>()
.Select(x => x.FW_DMF_or_Solid.ToString())
.ToArray();
Also, you should be able to replace your DistinctBy
code with 此外,您应该能够用您的
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());
}
string[] arrayOfSingleProperty =
listOfObjects
.Select(o => o.FW_DMF_or_Solid)
.OrderBy(o =>o)
.Distinct()
.ToArray();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.