c# - 如何独立获得每个属性的不同值

标签 c# performance linq distinct-values

我有大量生成的集合,我想独立获取每个属性的不同值:

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/

相关文章:

c# - 在 gridview asp.net c# 中创建超链接

javascript - 如何从 Controller 的 "<select></select>" View 中获取 "ActionResult"的值?

java - 高效的数据库操作

c++ - R stats::sd() 与 arma::stddev() 与 Rcpp 实现的性能

c# - 无法在 LINQ to Entities 查询中构造实体或复杂类型

c# - 如何使用应用程序域执行带有强制参数的程序集?

c# - 关于 BitConverter 中的 "GetBytes"实现

java - 从 String 中检索值的最快方法是什么?

c# - 如何返回 IQueryable<T>

c# - LINQ to SQL 查询+子查询中的基本类型错误