marshall marshall - 5 days ago 6
C# Question

Searching in ListArray C#

how 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'no this search method not good if list data too much data.

Answer

You can use linq

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