Showing posts with label list. Show all posts
Showing posts with label list. Show all posts

Saturday, 13 November 2010

Using Linq to Split a List

Started using more Linq and had to use it recently for splitting a list of items.

Basically I had to create a treeview of items and I didn't want to have to keep loading the items from a stored procedure everytime I needed to add items to a node.

So here's what I did instead, I used one stored procedure to create one list:
List<NodeItem> list1 = New List<NodeItem>();
list1.LoadListItems(); // this function uses stored procedure and loads list

And then I filter this list into as many other ones as I need (or create a loop and create a list for each node I want to add to), by doing the following:
int NodeID = CurrentNodeID;
List<NodeItem> subNodes = New List<NodeItem>();
subNodes = list1.Where(n => n.LinkedID == NodeID).ToList();

This preserves list1 and saves me from running another data query, sorted.