× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Compare lists to retrieve object properties that don't match

James Jensen
Feb 10, 2015
<blockquote> <p>How can I correctly compare two lists and return the objects where a specific property value does not exist in the other?</p> </blockquote> <p>Something like this?</p> <pre><code>manufacturerResult = (from t in manufacturerLevel // where a specific property value does not exist in the other where !validThresholds.Any( r =&gt; r.ThresholdType == t.ThresholdType) select t).ToList(); </code></pre> <blockquote> <p>My intent is to add the objects from manufacturerLevel to validThresholds where any object in validThreshold doesn't have the same ThresholdType value as any object in manufacturerLevel</p> </blockquote> <pre><code>validThresholds.AddRange( manufacturerLevel.Where(t =&gt; !validThresholds.Any( r =&gt; r.ThresholdType == t.ThresholdType))); </code></pre> <p>You may also want to consider whether what you're really trying to do is compile a <code>Set</code> of these objects. If you made <code>validThresholds</code> a <code>HashSet&lt;&gt;</code>, for example, with an <code>IEqualityComparer&lt;&gt;</code> based on the <code>ThresholdType</code>, you could simply <code>Add</code> all the items, and it would automatically ignore any whose <code>ThresholdType</code> was already represented in the collection.</p> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/22867306/Compare%20lists%20to%20retrieve%20object%20properties%20that%20don't%20match/22867382">Stack Overflow</a>.</p>
comments powered by Disqus