开发者

Using LINQ to find three or more matching records

First, I'll describe my table structure.

I have table, with 2 columns (ID and Root). This table is converted to a List of Nodes where the simple node structure is:

struct Node
{
    public int id;
    public int root;
}

I need to find all entries in this List where there's 3 or more roots equals.

Example:

struct TeleDBData
{
    public int ID;
    public int? RootID;
}

private void InitList()
{
    var eqList = new List<TeleDBData>();

    TeleDBData root = new TeleDBData();
    root.ID = 1;

    TeleDBData node1 = new TeleDBData();
    node1.ID = 2;
    node1.RootID = 1;

    TeleDBData node2 = new TeleDBData();
    node2.ID = 3;
    node2.RootID = 1;

    TeleDBData node3 开发者_如何学Go= new TeleDBData();
    node3.ID = 4;
    node3.RootID = 1;

    TeleDBData node4 = new TeleDBData();
    node4.ID = 5;
    node4.RootID = 2;

    eqList.Add(root);
    eqList.Add(node1);
    eqList.Add(node2);
    eqList.Add(node3);
    eqList.Add(node4);
}

After running the query, it will return node1, node2 and node3.

How can I find them using LINQ?


You just need to GroupBy accordingly:

var groups = eqList.GroupBy(n => n.RootID).Where(g => g.Count() >= 3);

foreach (var g in groups) {
    Console.Out.WriteLine("There are {0} nodes which share RootId = {1}",
                          g.Count(), g.Key);
    foreach (var node in g) {
        Console.Out.WriteLine("    node id = " + node.ID);
    }
}

See it in action.

Additional info:

In the code above, g is an IGrouping<int?, TeleDBData> so, by the documentation page definition, it's a collection of TeleDBData items that share a common key (which is an int?). groups is an IEnumerable<IGrouping<int?, TeleDBData>>, all of this is standard procedure for the Enumerable.GroupBy method.

The two things you would want to do with an IGrouping<,> is access its Key property to find the key and enumerate over it to process the grouped elements. We 're doing both of this in the above code.

As for the n in the GroupBy lambda, it simply represents each one of the items in eqList in turn; it follows that its type is TeleDBData. I picked n as the parameter name as an abbreviation of "node".

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜