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 = 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
GroupByaccordingly:See it in action.
Additional info:
In the code above,
gis anIGrouping<int?, TeleDBData>so, by the documentation page definition, it’s a collection ofTeleDBDataitems that share a common key (which is anint?).groupsis anIEnumerable<IGrouping<int?, TeleDBData>>, all of this is standard procedure for theEnumerable.GroupBymethod.The two things you would want to do with an
IGrouping<,>is access itsKeyproperty 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
nin theGroupBylambda, it simply represents each one of the items ineqListin turn; it follows that its type isTeleDBData. I pickednas the parameter name as an abbreviation of “node”.