का उपयोग स्पष्टीकरण के लिए, अन्य उत्तर पर एक नज़र डालें। मैं सिर्फ इस मुद्दे को संभालने का एक तरीका प्रदान कर रहा हूं।
आप this पसंद कर सकते हैं:
public class LambdaComparer<T>:IEqualityComparer<T>{
private readonly Func<T,T,bool> _comparer;
private readonly Func<T,int> _hash;
public LambdaComparer(Func<T,T,bool> comparer):
this(comparer,o=>0) {}
public LambdaComparer(Func<T,T,bool> comparer,Func<T,int> hash){
if(comparer==null) throw new ArgumentNullException("comparer");
if(hash==null) throw new ArgumentNullException("hash");
_comparer=comparer;
_hash=hash;
}
public bool Equals(T x,T y){
return _comparer(x,y);
}
public int GetHashCode(T obj){
return _hash(obj);
}
}
उपयोग:
public void Foo{
public string Fizz{get;set;}
public BarEnum Bar{get;set;}
}
public enum BarEnum {One,Two,Three}
var lst=new List<Foo>();
lst.Distinct(new LambdaComparer<Foo>(
(x1,x2)=>x1.Fizz==x2.Fizz&&
x1.Bar==x2.Bar));
तुम भी इसके चारों ओर लपेट शोर new LambdaComparer<T>(...)
बात लिख से बचने के लिए कर सकते हैं:
public static class EnumerableExtensions{
public static IEnumerable<T> SmartDistinct<T>
(this IEnumerable<T> lst, Func<T, T, bool> pred){
return lst.Distinct(new LambdaComparer<T>(pred));
}
}
उपयोग:
lst.SmartDistinct((x1,x2)=>x1.Fizz==x2.Fizz&&x1.Bar==x2.Bar);
एनबी: केवल Linq2Objects
स्रोत
2010-12-14 11:49:19
यह बहुत अच्छा काम किया। धन्यवाद। –
कृपया केवल लिंक करके जवाब न दें। उत्तर में प्रासंगिक कोड शामिल है। –
हाँ, मैं अब और नहीं करता लेकिन 2010 में मैंने इस अभ्यास पर ध्यान नहीं दिया। – Stilgar