简体   繁体   English

处理linq组的方法

[英]method to process linq group

I have a simple list of integers (some values repeated) and process with: 我有一个简单的整数列表(重复了一些值),并进行以下处理:

var groups = from n in numbers
    group n by n into numGroup
    where numGroup.Count()>1
    select numGroup;

I can iterate over the groups with nested loops directly after the linq, but I am having trouble writing a separate method to loop through them. 我可以在linq之后直接使用嵌套循环对组进行迭代,但是我很难编写一个单独的方法来遍历它们。 Here is what I have tried. 这是我尝试过的。

private void PrintGroups(IEnumerable groups, string title)
{
    int i = 0;
    foreach (var group in groups)
    {
        txt1.Text += "Group " + ++i + "\r\n"; ;
        foreach (var x in group)
               txt1.Text += "    " + x.ToString() + "\r\n"; ;
     }
}

The compiler doesn't like the inner foreach: 编译器不喜欢内部的foreach:

"foreach statement cannot operate on variables of type 'object' because 'object' does not contain a public definition for 'GetEnumerator'" “ foreach语句无法对'object'类型的变量进行操作,因为'object'不包含'GetEnumerator'的公共定义”

But the same code works inline with the linq. 但是相同的代码可以与linq内联。 Any suggestions? 有什么建议么?

It looks to me like you just need to change the type of your parameter: 在我看来,您只需要更改参数的类型即可:

private void PrintGroups(IEnumerable<IGrouping<int, int>> groups, string title)

However, aren't you really just interested in the key and the count? 但是,您真的不只是对键和数量感兴趣吗? After all, all the values in the group will be the same... 毕竟,该组中的所有值都是相同的...

private void PrintGroups(IEnumerable<IGrouping<int, int>> groups)
{
    StringBuilder builder = new StringBuilder();
    foreach (var group in groups)
    {
        builder.AppendFormat("Group {0}: {1}\r\n", group.Key, group.Count());
    }
    txt1.Text = builder.ToString();
}

In Linq one thinks in projections, here is an example where I project the group of numbers into a string which can be displayed to the user. 在Linq中,人们想到了投影,这是一个示例,其中我将数字组投影到可以显示给用户的字符串中。

 var nums = new List<int>() { 1, 1, 5, 6, 1, 5, 2 };

 nums.GroupBy (n => n)
     .Select (n => string.Format("Number {0} is found {1} times ({2})", n.Key, n.Count (), string.Join(",", n)))
     .ToList()
     .ForEach(strN => Console.WriteLine (strN));

/* Output

Number 1 is found 3 times (1,1,1)
Number 5 is found 2 times (5,5)
Number 6 is found 1 times (6)
Number 2 is found 1 times (2)

*/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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