Linq Distinct不能使用問題
Linq有一個功能是 .Distinct 可以去除重複項,但是直接使用的話貌似沒有什麼用。
比如一個資料表有 AAA , BBB , CCC , AAA , AAA , BBB , AAA , CCC
輸出之後還會是 AAA , BBB , CCC , AAA , AAA , BBB , AAA , CCC
這是因為並沒有做出一個比較表,因此
var ListData = new List<string>() {"AAA" , "BBB" , "CCC" ,"AAA" , "BBB" , "CCC" ,"AAA","AAA" };
var distinctData = ListData.Distinct(new Compare());
class Compare: IEqualityComparer<string>{
public bool Equals(string x , string y){
return x.Equals(y);
}
public int GetHashCode(string obj){
return obj.GetHashCode();
}
}
這樣的話就會變成 AAA BBB CCC了
但是這樣就只能適用於 string 假如丟 int 進去就會無法使用
public class PropertyComparer<T> : IequalityComparer<T>{
private PropertyInfo _PropertyInfo;
public PropertyComparer(string propertyName){
// get PropertyInfo type from T
_PropertyInfo = typeof(T).GetProperty(propertyName ,
BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.Public );
if (_PropertyInfo == null)
throw new ArgumentException(propertyName + "is null" + typeof(T));
}
public bool Equals(T x , T y){
object xValue = _PropertyInfo.GetValue(x , null);
object yValue = _PropertyInfo.GetValue(y , null);
if (xValue == null){
return yValue == null;
}
return xValue.Equals(yValue);
}
public int GetHashCode(string obj){
object propertyValue = _PropertyInfo.GetValue(obj , null);
if (propertyValue == null)
return 0;
else
return propertyValue.GetHashCode();
}
}
接著文章內有提到關於這個問題,有一個更好的解決方法,不用額外建立物件,使用擴充的方法解決Distinct。
public static class EnumerableExctender{
public static IEnumerable<TSource> Distinct<TSource , TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector){
HashSet<TKey> seenKeys = new HashSet<TKey>();
foreach (TSource element in source){
var elementValue = keySelector(element);
if (seenKeys.Add(elementValue)){
yield return element;
}
}
}
}
這樣的部分就可以使用
var distinctData = ListData.Distinct(ListData => ListData);
參考:
https://dotblogs.com.tw/larrynung/2012/09/18/74901#google_vignette
留言
張貼留言