Reputation: 46
I haven't worked with LINQ before, but I know how efficient it is.
I have created a List with an object which you can see below:
public sealed class Item
{
public long Start { private set; get; }
public long End { private set; get; }
public Item(string start, string end)
{
this.Start = Convert.ToInt64(start);
this.End = Convert.ToInt64(end);
}
}
This will be populated with DataSet
s containing round about 200k Items.
Now, I want to select the best single item between the properties 'Start' and 'End'.
this.ItemList.Add(new Item(100000, 100002));
this.ItemList.Add(new Item(100003, 100006));
this.ItemList.Add(new Item(100007, 100012));
this.ItemList.Add(new Item(100013, 100026));
this.ItemList.Add(new Item(100027, 100065));
From another tool, I've got the value: 100009
How can I get the object new Item(100007, 100012)
back with LINQ? Does anyone have any suggestions?
Upvotes: 1
Views: 6057
Reputation: 172478
Sounds like a simple Where
query should suffice:
long value = 100009;
var found = ItemList.Where(item => item.Start <= value && item.End >= value);
This will yield an IEnumerable<Item>
containing all matching items. You can use .First()
/.FirstOrDefault()
to get the first matching item or continue to filter the result until you get the one you want.
Note that, if you really have 200k entries, a List might not be the most efficient data structure to search in (you have O(n) complexity). If performance is an issue, you might want to consider using a SortedList
and a binary search algorithm instead.
Upvotes: 5