无论如何将2个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();
答案 0 :(得分:4)
按行执行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);
答案 1 :(得分:4)
回答你的问题。没有内置的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);
}
}
您可以创建命名的返回类型而不是Tuple,以便更轻松地使用。
示例用法如下:
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();
答案 2 :(得分:0)
您可以尝试选择匿名类型:
from string row in myList[i]
where row.Length > 0
select new {
DistCount = row.Distinct().Count(),
NormCount = row.Count()
}