开发者

how to write this into linq to object query?

开发者 https://www.devze.com 2022-12-21 16:38 出处:网络
from a list, which got 3 attributes I want to return a new list of that class where attribut1 recurrence in the list equals X

from a list, which got 3 attributes I want to return a new list of that class where attribut1 recurrence in the list equals X

for an example this;

1,a,b

1,c,d

1,e,f

2,a,b

2,c,d

3,a,b

3,c,d

3,e,f

4,a,b

5,a,b

5,c,d

5,e,f

6,a,b

6,e,f

where X = 1 would return that list

4,a,b

where X = 2 would return that list

2,a,b

2,c,d

6,a,b

6,e,f

where X = 3 would return that list

1,a,b

1,c,d

1,e,开发者_StackOverflowf

3,a,b

3,c,d

3,e,f

5,a,b

5,c,d

5,e,f


Perfect case for grouping!

var groups = list.GroupBy(s => s.Attribute1);
var recur_1 = groups.Where(g => g.Count() == 1).SelectMany(s => s);
var recur_2 = groups.Where(g => g.Count() == 2).SelectMany(s => s);
var recur_3 = groups.Where(g => g.Count() == 3).SelectMany(s => s);


seq.Where(l => seq.Count(i => i.attrib1 == l.attrib1) == X);


public static void Test()
{
    var list = new[]
                {
                    new {p1 = 1, p2 = 'a', p3 = 'b'},
                    new {p1 = 1, p2 = 'c', p3 = 'd'},
                    new {p1 = 1, p2 = 'e', p3 = 'f'},
                    new {p1 = 2, p2 = 'a', p3 = 'b'},
                    new {p1 = 2, p2 = 'c', p3 = 'd'},
                    new {p1 = 3, p2 = 'a', p3 = 'b'},
                    new {p1 = 3, p2 = 'c', p3 = 'd'},
                    new {p1 = 3, p2 = 'e', p3 = 'f'},
                    new {p1 = 4, p2 = 'a', p3 = 'b'},
                    new {p1 = 5, p2 = 'a', p3 = 'b'},
                    new {p1 = 5, p2 = 'c', p3 = 'd'},
                    new {p1 = 5, p2 = 'e', p3 = 'f'},
                    new {p1 = 6, p2 = 'a', p3 = 'b'},
                    new {p1 = 6, p2 = 'e', p3 = 'f'}


                };

    for (int i = 1; i <= 3; i++)
    {
        var items = from p in list
                 group p by p.p1
                 into g
                    where g.Count() == i
                    from gi in g
                    select gi;

        Console.WriteLine();
        Console.WriteLine("For " + i);
        Console.WriteLine();
        foreach (var x in items)
        {
            Console.WriteLine("{0},{1},{2}", x.p1, x.p2, x.p3);
        }

    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号