我有一个Employee对象列表
public struct Employee { public string role; public string id; public int salary; public string name; public string address; }我想获取name和id属性与条件匹配的对象。 我试过用这个:
List<Employee> EleList = new List<Employee>(); var employee= EleList.Find(sTag => sTag.id == 5b && sTag.name== "lokendra");这非常耗时,因为列表大小介于20000-25000之间。是否有其他方法可以检索结果。 请指导我这个。
I have a list of objects Employee
public struct Employee { public string role; public string id; public int salary; public string name; public string address; }I want to get the object where the name and id property matches the condition. I have tried using this:
List<Employee> EleList = new List<Employee>(); var employee= EleList.Find(sTag => sTag.id == 5b && sTag.name== "lokendra");This is pretty time consuming because the list size is between 20000-25000.Is there any other way to retrieve the result. Please guide me on this.
最满意答案
您可以使用适当的集合类型(例如字典)来加快速度。
如果Employee的id是唯一的,则可以将其用作Dictionary<string, Employee>类型的Dictionary<string, Employee>的键。 搜索看起来像这样:
Employee employee; if(dict.TryGetValue("5b", out employee) && employee.name == "lokendra") // employee found else // employee not found创建字典将如下所示:
dict = EleList.ToDictionary(x => x.id, x => x);如果它不是唯一但合理集中(只有少数具有相同id的员工),则可以将其用作Dictionary<string, List<Employee>>类型Dictionary<string, List<Employee&t;>的键。 搜索看起来像这样:
Employee GetEmployee(string id, string name) { List<Employee> employees; if(!dict.TryGetValue(id, out employees)) return null; return employees.FirstOrDefault(x => x.name == name); }创建字典将如下所示:
dict = EleList.GroupBy(x => x.id) .ToDictionary(x => x.Key, x => x.ToList());请注意: 在这两种情况下,您应该只创建一次字典而不是每次搜索。 所以基本上,你应该有字典而不是EleList 。
You can speed this up by using an appropriate collection type, e.g. a Dictionary.
If the id of the Employee is unique, you can use it as the key in a dictionary of type Dictionary<string, Employee>. Searching would look like this:
Employee employee; if(dict.TryGetValue("5b", out employee) && employee.name == "lokendra") // employee found else // employee not foundCreating the dictionary would look like this:
dict = EleList.ToDictionary(x => x.id, x => x);If it is not unique but reasonably focused (only a few employees with the same id), you can use it as a key in a dictionary of type Dictionary<string, List<Employee>>. Searching would look like this:
Employee GetEmployee(string id, string name) { List<Employee> employees; if(!dict.TryGetValue(id, out employees)) return null; return employees.FirstOrDefault(x => x.name == name); }Creating the dictionary would look like this:
dict = EleList.GroupBy(x => x.id) .ToDictionary(x => x.Key, x => x.ToList());Please note: In both cases, you should create the dictionary only once and not for every search. So basically, instead of EleList you should have the dictionary.
更多推荐
发布评论