[英]Count and distinct count in one LINQ expression
无论如何将两个linq表达式合并为一个? 即,一个LINQ表达式将DistCount和NormCount都返回到2个单独的int变量中。
DistCount = (from string row in myList[i]
where row.Length > 0
select row).Distinct().Count();
NormCount = (from string row in myList[i]
where row.Length > 0
select row).Count();
按行group
。 然后,您将拥有不同的计数(组的数量)和总数( Count
的总和)
var q = (from string row in myList[i]
where row.Length > 0
group row by row into rowCount
select new {rowCount.Key, rowCount.Count})
int distinct = q.Count();
int total = q.Sum(r=>r.Count);
回答你的问题。 没有内置的linq表达式。
边注。 如果你真的需要它,你可以创建一个。
public static class Extensions
{
public static Tuple<int, int> DistinctAndCount<T>(this IEnumerable<T> elements)
{
HashSet<T> hashSet = new HashSet<T>();
int count = 0;
foreach (var element in elements)
{
count++;
hashSet.Add(element);
}
return new Tuple<int, int>(hashSet.Count, count);
}
}
您可以创建命名返回类型而不是元组,以便更轻松地使用。
示例用法如下:
var distinctAndCount = (from string row in myList[i]
where row.Length > 0
select row
).DistinctAndCount();
或者我个人更愿意写它:
var distinctAndCount = myList[i].Where(row => row.Length > 0).DistinctAndCount();
您可以尝试选择匿名类型:
from string row in myList[i]
where row.Length > 0
select new {
DistCount = row.Distinct().Count(),
NormCount = row.Count()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.