【发布时间】:2017-11-19 12:37:32
【问题描述】:
在 C# 中使用 Contains 方法是否有更快的替代方法?
这是一个看起来像我正在尝试做的示例,但我读到 Contains 是一种昂贵的方法,我想找到更好的替代方法,因为速度很重要。
public List<Guid> getCumulativeListByUsername(string username)
{
List<Guid> CombinedList = new List<Guid>();
List<Guid> ListA = new List<Guid>();
List<Guid> ListB = new List<Guid>();
ListA = getListAFromDatabase(username);
ListB = getListBFromDatabase(username);
CombinedList = ListA;
foreach (Guid x in ListB)
{
if (!CombinedList.Contains(x))
{
CombinedList.Add(x);
}
}
return CombinedList;
}
如果你也能解释你的推理,我们将不胜感激。
【问题讨论】:
-
“我读到 Contains 是一种昂贵的方法” - 你在实践中注意到了吗?你在哪里读到的,他们有没有提供替代品?如果不是,您的研究表明了什么?对此的实际答案是使用 HashSet 或 Dictionary,我相信您一定也读过吗?
-
您是否遇到任何实际的性能问题?
-
如果你从一个数据库中拉出 2 个列表,或者在那里合并,数据库擅长集合操作。
-
为什么不
Intersect?