比较两个列表的最快方法<CustomObject>
Fastest way to compare two List<CustomObject>
我有两个 List<CustomObject>
,分别是 list1 和 list2
public class CustomObject
{
public string foo { get; set; }
public string bar{ get; set; }
}
目标是生成一个新列表,其中包含列表 2 中 modified/added 的所有条目。
因为这些列表可能会变得很长,循环遍历它们不是一种选择...
有什么想法吗?
这是一种传统的方法:
public class CustomObject : IComparable
{
public string foo { get; set; }
public string bar{ get; set; }
public int CompareTo(CustomObject o)
{
if (this.foo == o.foo && this.bar == o.bar) return 0;
//We have to code for the < and > comparisons too. Could get painful if there are a lot of properties to compare.
if (this.Foo == o.Foo) return (this.Bar.CompareTo(o.Bar));
return this.Foo.CompareTo(o.Foo);
}
}
然后使用Linq.Except:
listA.Except(listB)
添加另一个答案以适应评论中出现的一些其他 NFR:
- 可以通过哈希码识别对象
- 列表很大,所以性能是个问题
- 想法是将旧列表与新列表进行比较,看看是否弹出了任何新的哈希码。
您需要将对象存储在字典中:
var list = new Dictionary<string, CustomObject>();
添加它们时,提供散列作为键:
list.Add(customObject.Hash, customObject);
要扫描新的:
var difference = new List<CustomObject>();
foreach (customObject o in newList)
{
if (oldList.ContainsKey(o.Hash)) difference.Add(o);
}
Log(String.Format("{0} new hashes found.", difference.Count));
通过使用字典,您可以利用键存储在散列中的方式 table。在散列 table 中查找项目比仅进行扫描和比较之类的事情要快。我相信这将是 O(n*log(n)) 而不是 O(n^2).
我有两个 List<CustomObject>
,分别是 list1 和 list2
public class CustomObject
{
public string foo { get; set; }
public string bar{ get; set; }
}
目标是生成一个新列表,其中包含列表 2 中 modified/added 的所有条目。
因为这些列表可能会变得很长,循环遍历它们不是一种选择...
有什么想法吗?
这是一种传统的方法:
public class CustomObject : IComparable
{
public string foo { get; set; }
public string bar{ get; set; }
public int CompareTo(CustomObject o)
{
if (this.foo == o.foo && this.bar == o.bar) return 0;
//We have to code for the < and > comparisons too. Could get painful if there are a lot of properties to compare.
if (this.Foo == o.Foo) return (this.Bar.CompareTo(o.Bar));
return this.Foo.CompareTo(o.Foo);
}
}
然后使用Linq.Except:
listA.Except(listB)
添加另一个答案以适应评论中出现的一些其他 NFR:
- 可以通过哈希码识别对象
- 列表很大,所以性能是个问题
- 想法是将旧列表与新列表进行比较,看看是否弹出了任何新的哈希码。
您需要将对象存储在字典中:
var list = new Dictionary<string, CustomObject>();
添加它们时,提供散列作为键:
list.Add(customObject.Hash, customObject);
要扫描新的:
var difference = new List<CustomObject>();
foreach (customObject o in newList)
{
if (oldList.ContainsKey(o.Hash)) difference.Add(o);
}
Log(String.Format("{0} new hashes found.", difference.Count));
通过使用字典,您可以利用键存储在散列中的方式 table。在散列 table 中查找项目比仅进行扫描和比较之类的事情要快。我相信这将是 O(n*log(n)) 而不是 O(n^2).