2012-02-18 80 views
3

无论如何要将2个linq表达式合并为一个?即所以一个LINQ表达式会将DistCount和NormCount都返回到2个独立的int变量中。一个LINQ表达式中的计数和不同计数

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

'变种最终=新{DistCount = 1,NormCount = 2};' – 2012-02-18 23:46:22

回答

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); 
+0

类型隐藏代码的意图,将需要放入一个名称不错的单独方法中或评论。性能也值得怀疑。 – 2012-02-19 00:05:50

+0

在q末尾记住一个“ToList”,或者你将整个小组做两次 – Cine 2013-08-20 02:40:21

0

你可以尝试选择一个匿名类型:

from string row in myList[i] 
where row.Length > 0 
select new { 
    DistCount = row.Distinct().Count(), 
    NormCount = row.Count() 
} 
+0

row.Distinct().Count()将计算字符串行中不同字符的数量,而不是作者需要的数量 – 2012-02-19 00:01:58

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); 
    } 
} 

您可以创建您的指定返回类型而不是元组,以便更容易使用。

用法示例会像:

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();