2016-11-27 53 views
1

什么是从C#中的列表数组中搜索数据的最快方法?在ListArray中搜索C#

我的代码:

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); 
    } 
} 

我知道这个搜索方法并不好,如果列表数据中包含太多的数据。

+0

“最快”是什么意思? :如果您运行代码,快速开发还是快速? – Fruchtzwerg

+0

@Fruchtzwerg最快≙运行速度最快;最简单≙最快的代码。 – devRicher

+0

如果'Initial'在水果中是唯一的;这可能是更好的使用'Dictionary ' – Sehnsucht

回答

2

如果你想要一个 “快” 的解决方案,你应该使用foreach而不是LINQ。该解决方案可以提高你的性能比较了很多:

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

你可以得到一些有关职位LINQ性能的更多信息,如

+0

感谢**快速**解决方案。 ;) – devRicher

+0

@devRicher - 感谢“快速”和“简单”的提示:-) – Fruchtzwerg

+0

感谢您的快速解决方案。 ;) – marshall

1

您可以使用linq

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

谢谢,这是非常简单的 – marshall

+1

,但不是很快... – Fruchtzwerg

+1

为什么问题被标记为[linq]时,你可以使用linq? – devRicher

0

最好的(和o最好)告诉某种情况最快的方法是用不同的算法对其进行基准测量。你已经在这里有两个答案/方法(LINQ和foreach)。他们两人的时间,然后选择更快的一个。

换句话说:测量你的代码使你比那些认为他们太聪明而无法测量的人更有优势。 ;)

为了进一步加快速度,您可能需要考虑保持列表排序,然后在列表中进行二进制搜索。它增加了插入的时间,因为你必须在插入后排序列表,但它应该加快搜索过程。但是,再说一次:不要只听我的话,测量它!