【问题标题】:The fast way to select the elements in a list which a property is in another list在列表中选择属性在另一个列表中的元素的快速方法
【发布时间】:2014-11-23 13:08:58
【问题描述】:

我有这样的课,

class Test
{
    public int ID { get; set; }
    public string Name { get; set; }
}

我也有一个 List ids;

我想选择列表中其 ID 在列表 ID 中的所有元素。我目前的解决方案是这样的:

var v = from t in tests where ids.Contains(t.ID) select t;

如果List的数量很大,超过10000条,是不是一种有效的方法?

谢谢

【问题讨论】:

  • 多大是多大?列表中有多少元素?您是否已经以某种方式衡量了性能?
  • 如果你有一个列表,那么你总是需要检查所有条目,无论如何都需要 O(n)。唯一可以更快的是某种具有 O(1) 访问权限的字典或地图。
  • 如果您按 id 对两个列表进行排序,则可以线性进行搜索。但是字典当然会更快。
  • 列表中的元素超过10000,我还没有做任何性能测试。

标签: c# algorithm linq list


【解决方案1】:

你可以试试这个:

var lookup = ids.ToDictionary(x => x);
var matching = tests.Where(t => lookup.ContainsKey(t.ID));

只要ids 不包含任何重复值,这将起作用。

或者(更快,根据下面的 cmets):

var lookup = new HashSet<int>(ids);
var matching = tests.Where(t => lookup.Contains(t.ID));

即使有重复的 ID,这也可以工作(再次,请参阅下面的 cmets)。

【讨论】:

  • 或者只是var lookup = new HashSet&lt;int&gt;(ids); var matching = tests.Where(t =&gt; lookup.ContainsKey(t.ID));。匹配应该是等价的,但是创建HashSet 而不是DictionaryLookup 应该快得多。 --(在我的系统上大约是三倍)。
  • 另外,HashSet 将自动“忽略”重复项。 -- 你可以通过var lookup = ids.Distinct().ToDictionary(x =&gt; x);将它们过滤到字典中
【解决方案2】:

列表项 = new List();

items.Find(p => p == "blah");

应该是更好的方法

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-28
    • 1970-01-01
    • 1970-01-01
    • 2014-07-31
    • 2018-08-29
    • 1970-01-01
    • 2016-02-03
    • 2017-06-05
    相关资源
    最近更新 更多