我有大量生成的集合,我想独立获取每个属性的不同值:
IEnumerable<MyClass> collection = ...;
var prop1Values = collection.Select(i => i.Prop1).Distinct();
var prop2Values = collection.Select(i => i.Prop2).Distinct();
var prop3Values = collection.Select(i => i.Prop3).Distinct();
如何在不多次枚举集合的情况下获取它?寻找最直观的解决方案:)
最佳答案
您可以尝试在单个 foreach
中完成在 HashSet<T>
的帮助下小号:
//TODO: put the right types for TypeOfProp1, TypeOfProp2, TypeOfProp3
var prop1Values = new HashSet<TypeOfProp1>();
var prop2Values = new HashSet<TypeOfProp2>();
var prop3Values = new HashSet<TypeOfProp3>();
foreach (var item in collection) {
prop1Values.Add(item.Prop1);
prop2Values.Add(item.Prop2);
prop3Values.Add(item.Prop3);
}
关于c# - 如何独立获得每个属性的不同值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53395206/