1

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 DataSets 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?

ataravati
  • 8,891
  • 9
  • 57
  • 89
  • What if given value fits two items as difference to both is equal? In particular what happens when the provided value is exactly between the end of one and the start of the next interval? – MakePeaceGreatAgain Feb 16 '16 at 13:56
  • It's not clear what your criteria is - do you want to find all objects where start and end are both between two arbitrary values? – D Stanley Feb 16 '16 at 13:57
  • Define best. Your question is not clear. – ataravati Feb 16 '16 at 16:34

1 Answers1

4

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.

Community
  • 1
  • 1
Heinzi
  • 167,459
  • 57
  • 363
  • 519