How to write this in linq to query an object?

from the list that received 3 attributes I want to return a new list of this class, in which the attribute referut1 in the list is equal to X

for example:

1, a, b
1, c, g
1, d, e
2, a, b
2, c, g
3, a, b
3, c, g
3, d, e
4, a, b
5, a, b
5, c, d
5, d, e
6, a, b
6, d, e

where X = 1 will return this list

4, a, b

where X = 2 will return this list

2, a, b
2, c, d
6, a, b
6, e, f

where X = 3 will return this list

1, a, b
1, c, g
1, d, e
3, a, b
3, c, g
3, d, e
5, a, b
5, c, g
5, e, f

+3
3

!

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);
+3
seq.Where(l => seq.Count(i => i.attrib1 == l.attrib1) == X);
+1
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

Source: https://habr.com/ru/post/1734316/


All Articles