简体   繁体   English

一个LINQ表达式中的计数和不同计数

[英]Count and distinct count in one LINQ expression

Is there anyway to combine the 2 linq expressions into one? 无论如何将两个linq表达式合并为一个? Ie so one LINQ expression will return both the DistCount and the NormCount into the 2 separate int variables. 即,一个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();

do a group by row. 按行group You'll then have the distinct count (# of groups) and the total (sum of Count s) 然后,您将拥有不同的计数(组的数量)和总数( 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);

To answer your question. 回答你的问题。 There's no built-in linq expression for that. 没有内置的linq表达式。

Side note. 边注。 If you really need it you can create one. 如果你真的需要它,你可以创建一个。

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

You can create your named return type instead of Tuple to make the usage easier. 您可以创建命名返回类型而不是元组,以便更轻松地使用。

Example usage will look like: 示例用法如下:

   var distinctAndCount = (from string row in myList[i]
                              where row.Length > 0 
                              select row
                             ).DistinctAndCount();

Or as I personally would prefer to write it: 或者我个人更愿意写它:

   var distinctAndCount = myList[i].Where(row => row.Length > 0).DistinctAndCount();

You might try selecting an anonymous type: 您可以尝试选择匿名类型:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM