1

What is the fastest method for searching data from list array in C#?

My code:

public class fruits
{
    public string Initial;
    public string Fruit;
    public fruits(string initials, string names)
    {
        Initial = initials;
        Fruit = names;
    }
}

// load
List<fruits> List = new List<fruits>();

List.Add(new fruits("A", "Apple"));
List.Add(new fruits("P", "Pineapple"));
List.Add(new fruits("AP", "Apple Pineapple"));


//combo box select text
var text = combobox.SelectText();
for (int i=0; i<list.Count(); i++)
{
    if (list[i].Fruit == text)
    {
        MessageBox.Show(list[i].Initial);
    }
}

I know this search method is not good, if list data contains too much data.

3
  • What do you mean with "fastest" ? : Fast do develop or fast if you run the code? Commented Nov 27, 2016 at 11:33
  • @Fruchtzwerg Fastest ≙ fastest running; Easiest ≙ fastest to code. Commented Nov 27, 2016 at 11:45
  • if Initial is unique among fruits ; it could be better to use a Dictionary<string, fruits> Commented Nov 27, 2016 at 19:59

3 Answers 3

2

If you want a "fast" solution, you should use a foreach instead of LINQ. This solution can improve your perfomance a lot:

fruits firstOrDefault = null:
foreach (fruits f in List)
{
    if (f.Fruit == text)
    {
        FirstOrDefault = f;
        break;
    }
}

You can get few more information about the LINQ performance in posts like

Sign up to request clarification or add additional context in comments.

2 Comments

@devRicher - thanks for the "fast" and "easy" hint :-)
Thanks for a fast solution. ;)
1

You can use linq

 var result = List.FirstOrDefault(q => q.Fruit == text );
 MessageBox.Show(result.Initial);

3 Comments

Why is the answer description "You can use linq" when the question is tagged [linq]?
because I know what it linq from another forum. haha
@marshall Even though it is not the fastest, it is another answer for your question
0

The best (and only) way to tell what method is fastest for a certain situation is to actually benchmark/measure it with different algorithms. You already have two answers/approaches here (LINQ and foreach). Time both of them and then pick the faster one.

Or in other words: Measuring your code gives you an advantage over those people who think they are too smart to measure. ;)

To speed things up further you might want to consider to keep the list sorted and then do a binary search on the list. It increases the time for insertion, because you have to sort the list after inserts, but it should speed up the search process. But then again: Do not just take my word for it, measure it!

Comments

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.