我正在寻找最有效的代码方式。我有一个int或字符串列表,我需要知道该列表中的一个值是否包含在第二个集合中。
如果我在第二个系列中使用字典,那么我会提出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]);
}
另一方面,我可以使用另一个List进行第二次收集,然后我推出了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]);
}
有人可以告诉我这里最有效的方式是什么?
答案 0 :(得分:1)
要找出最快的一个,你应该进行性能测试。
但这是混音的另一种选择,可能会更快:
var lst = new HashSet<int>();
var lstIds = new HashSet<int>();
var hasMatch = lst.Intersect(lstIds).Any();