根据特定属性比较两个列表 [英] Comparing two lists according to specific properties
问题描述
我该如何比较2个列表,并根据具体属性选择不匹配的项目
how can i compare 2 lists and have the not matching items but according to the specifics properties
public partial class Cable : StateObject
{
public int Id { get; set; }
public int CablePropertyId { get; set; }
public int Item { get; set; }
public int TagNo { get; set; }
public string GeneralFormat { get; set; }
public string EndString { get; set; }
public string CableRevision { get; set; }
}
如果要使用,我想根据CablePropertyId,TagNo和CableRevision比较完成的结果
I want to comparision accomplished accoring to the CablePropertyId,TagNo and CableRevision, if i use
var diffCables = sourceCables.Except(destinationCables).ToList();
将整个属性相互比较.我该怎么办?
the whole properties are compared to each other . how can i do that?
推荐答案
使用带有自定义EqualityComparer的方法除外的Linq.
Use Linq except method with custom EqualityComparer.
http://msdn.microsoft. com/en-us/library/bb336390(v = vs.110).aspx
class CableComparer : IEqualityComparer<Cable>
{
public bool Equals(Cable x, Cable y)
{
return (x.CablePropertyId == y.CablePropertyId && ...);
}
public int GetHashCode(Cable x) // If you won't create a valid GetHashCode based on values you compare on, Linq won't work properly
{
unchecked
{
int hash = 17;
hash = hash * 23 + x.CablePropertyID;
hash = hash * 23 + ...
}
return hash;
}
}
var diffCables = sourceCables.Except(destinationCables, new CableComparer());
此外,对结果执行ToList()
并不是真正必要的.在大多数情况下,您可以仅对Linq查询IEnumerable
的结果进行操作,而无需指定确切的类型.这样,您就不会在不必要的ToList()
操作上浪费性能.
Also, ToList()
operation on the result isn't really necessary. Most of the time you can just operate on the result of Linq query IEnumerable
without specifying the exact type; this way you won't waste performance on unneeded ToList()
operation.
顺便说一句,其他一些人提出了带有简单lambda的基于Where的查询.这样的解决方案更容易阅读(我认为),但优化程度也较低:它强制执行n ^ 2检查,而IEqualityComparer允许使用GetHashCode()
方法使Linq达到最佳状态.这是关于GetHashCode重要性的绝佳答案,这是
By the way, a couple of others proposed Where-based queries with simple lambda. Such solution is easier to read (in my opinion), but it's also less optimized: it forces n^2 checks, while IEqualityComparer allows Linq to be more optimal because of GetHashCode()
method. Here's a great answer on importance of GetHashCode, and here's a great guide on writing GetHashCode()
override.
这篇关于根据特定属性比较两个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!