2

I have a list which contains more than 75 thousand object. To search item from list currently I am using following code.

from nd in this.m_ListNodes
where
   nd.Label == SearchValue.ToString()
   select
   nd;

Is this code is efficient?

1
  • 1
    @Marco: the OP has asked a total of 5 questions (this one included) with quite few answers on them. It could be that there have not been good enough answers yet. Commented Apr 15, 2011 at 7:47

2 Answers 2

12

How often do you need to search the same list? If you're only searching once, you might as well do a straight linear search - although you can make your current code slightly more efficient by calling SearchValue.ToString() once before the query.

If you're going to perform this search on the same list multiple times, you should either build a Lookup or a Dictionary:

var lookup = m_ListNodes.ToLookup(nd => nd.Label);

or

var dictionary = m_ListNodes.ToDictionary(nd => nd.Label);

Use a dictionary if there's exactly one entry per label; use a lookup if there may be multiple matches.

To use these, for a lookup:

var results = lookup[SearchValue.ToString()];
// results will now contain all the matching results

or for a dictionary:

WhateverType result;
if (dictionary.TryGetValue(SearchValue.ToString(), out result))
{
    // Result found, stored in the result variable
}
else
{
    // No such item
}
Sign up to request clarification or add additional context in comments.

Comments

4

No. It would be better if you used a Dictionary or a HashSet with the label as the key. In your case a Dictionary is the better choice:

var dictionary = new Dictionary<string, IList<Item>>();

// somehow fill dictionary

IList<Item> result;
if(!dictionary.TryGetValue(SearchValue.ToString(), out result)
{
    // if you need an empty list 
    // instead of null, if the SearchValue isn't in the dictionary
    result = new List<Item>(); 
}

// result contains all items that have the key SearchValue

4 Comments

A HashSet wouldn't work, if he's trying to find the item. A dictionary will work if there's only a single match, but fail if multiple items have the same label.
I try with dictionary still it takes time. The code is : from nd in this.m_NodeDict where nd.Key == SearchValue.ToString() select nd.Value;
@JonSkeet: The Dictionary fails only, if you are using it wrong. If there are several items with the same label, use a Dictionary<string, IList<Item>>. Problem solved.
@Daniel: At that point, why not just use a Lookup? I'd rather reuse code that's already written than write it myself :) I guess my point was mostly that you ought to distinguish between the two cases (unique label or not).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.