【发布时间】:2013-12-10 08:58:44
【问题描述】:
我正在寻找最有效的编码方式。我有一个整数或字符串列表,我需要知道该列表中的某个值是否包含在第二个集合中。
如果我对第二个集合使用字典,那么我得出了 5 种不同的搜索方式:
Dictionary<int, bool> dicSource = new Dictionary<int, bool>();
List<int> lstSearch = new List<int>();
// First approuce
var ids = dicSource.Keys.Intersect(lstSearch);
bool hasMatch1 = ids.Any();
//Second approuce
bool hasMatch2 = dicSource.Any(x => lstSearch.Any(y => y == x.Key));
//Third approuce
bool hasMatch3 = dicSource.Select(x => x.Key).Intersect(lstSearch).Any();
//Fourth approuce
bool hasMatch4 = (dicSource.Where(x => lstSearch.Contains(x.Key)).Count() > 0);
//Fifth approuce
for (int i = 0; i < lstSearch.Count; i++)
{
bool hasMatch5 = dicSource.ContainsKey(lstSearch[i]);
}
另一方面,我可以为第二个集合使用另一个列表,然后我得出了 5 种不同的搜索方式:
List<int> lst = new List<int>();
List<int> lstIds = new List<int>();
// First approuce
var ids = lst.Intersect(lstIds);
bool hasMatch1 = ids.Any();
//Second approuce
bool hasMatch2 = lst.Any(x => lstIds.Any(y => y == x));
//Third approuce
bool hasMatch3 = lst.Select(x => x).Intersect(lstIds).Any();
//Fourth approuce
bool hasMatch4 = (lst.Where(id => lstIds.Contains(id)).Count() > 0);
//Fifth approuce
for (int i = 0; i < lstSearch.Count; i++)
{
bool hasMatch5 = lstSource.Contains(lstSearch[i]);
}
谁能告诉我这里最有效的使用方法是什么?
【问题讨论】:
-
您有 4 个选项。伟大的!你为什么不自己测试一下?
标签: c# performance list dictionary