例如现在有个结构:struct MyStruct
{
public int ID;
public string Name;
}然后还有一个LIST集合:List<MyStruct> MyStructs = new List<MyStruct>(10);然后往集合中添加结构数据,那么如何快速找到自己需要的结构呢?比如我需要在集合中找到ID=999的那个结构体,有什么快速的方法?
使用foreach(MyStruct tempMyStruct in MyStructs)
{
if (tempMyStruct.ID == 999)
{ }
}
会很慢……尤其是集合比较大的时候!现在的需求是这样的:每个用户的信息存储在一个STRUCT中,然后再将这个STRUCT ADD到一个LIST中,这样就形成了一个列表,然后我需要在其中找到自己需要的,请问有什么好的解决方案呢?
{
public int ID;
public string Name;
}然后还有一个LIST集合:List<MyStruct> MyStructs = new List<MyStruct>(10);然后往集合中添加结构数据,那么如何快速找到自己需要的结构呢?比如我需要在集合中找到ID=999的那个结构体,有什么快速的方法?
使用foreach(MyStruct tempMyStruct in MyStructs)
{
if (tempMyStruct.ID == 999)
{ }
}
会很慢……尤其是集合比较大的时候!现在的需求是这样的:每个用户的信息存储在一个STRUCT中,然后再将这个STRUCT ADD到一个LIST中,这样就形成了一个列表,然后我需要在其中找到自己需要的,请问有什么好的解决方案呢?
delegate代理
List<T> lst=new List<T>();
List<T> lst2=lst.FindAll(delegate(T t){});
Hashtable ht = new Hashtable();
ht.Add("id", "name");
Hashtable中的key用来存ID,ID要是唯一的,后面的存name或其它结构,要查询时 ht.Contains("id")进行判断,要区取"id"对应的结值就 string s = (string)ht["id"];你看看是否满足你的要求
item.ID = 1;
item.Name = "item";
Dictionary<int, MyStruct> list = new Dictonary<int, MyStruct>();
list.Add(item.ID, item);
Label1.Text = list[item.ID].Name;
你说的情况没有实际测试过,你测试下就知道了
请问各位大大还有什么好的解决方案吗?
假设你已经给这个泛型集合填充了结构,
using System.Linq;(必须引入)
static void Main(string[] args)
{
List<MyStruct> MyStructs = new List<MyStruct>{
.............
..........
..........(填充)
...........
............};
var myst=from c in MyStructs where c.ID=999 select c;
foreach(var my in myst)
{
int i=0;
MyStruct[myst.count] MyStruct[i]=(MyStruct)my;
i++;}
}ok就这样解决了,linq是专门为这一类问题建了的查询,很方便吧
!
如果你不是那就这就用foreach进行循环,可能会慢!
如果你的id唯一,无论hashtable还是dictionary的性能都不错。