【问题标题】:Count and distinct count in one LINQ expression一个 LINQ 表达式中的计数和不同计数
【发布时间】:2012-02-18 23:34:25
【问题描述】:

有没有办法将 2 个 linq 表达式合并为一个? IE。所以一个 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();

【问题讨论】:

  • var final = new {DistCount=1,NormCount=2};

标签: c# .net linq c#-4.0


【解决方案1】:

按行执行group。然后,您将获得不同的计数(组数)和总数(Counts 的总和)

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

【讨论】:

  • 有点隐藏代码的意图,需要放在一个单独的方法中,名字好或注释。性能也值得怀疑。
  • 在 q 的末尾记住一个“ToList”,否则你将整个组做两次
【解决方案2】:

回答您的问题。没有内置的 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();

【讨论】:

    【解决方案3】:

    您可以尝试选择匿名类型:

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

    【讨论】:

    • row.Distinct().Count() 会统计字符串行中不同字符的个数,不是作者需要的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 2013-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多