marshall
marshall

Reputation: 74

Searching in ListArray C#

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.

Upvotes: 1

Views: 98

Answers (3)

Striezel
Striezel

Reputation: 3758

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!

Upvotes: 0

Fruchtzwerg
Fruchtzwerg

Reputation: 11399

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

Upvotes: 2

Sajeetharan
Sajeetharan

Reputation: 222722

You can use linq

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

Upvotes: 1

Related Questions