簡體   English   中英

一個LINQ表達式中的計數和不同計數

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM