1,对集合Distinct方法
public static IEnumerable<TSource> Distinct<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector) { HashSet<TKey> keys = new HashSet<TKey>(); foreach (var i in source) { if (keys.Add(selector(i))**重点内容**) { yield return i; } } }2,扩展方法将任意集合转成DataSet
/// <summary> /// 转换成DataSet,若被转换对象为Null,则返回Null。 /// </summary> /// <param name="obj">一个对象实例</param> /// <returns>返回DataSet,若被转换对象为Null,则返回Null。</returns> public static DataSet ToDataSet(this object obj) { if (obj == null) return null; if (obj is DataSet) { return obj as DataSet; } DataSet ds = new DataSet(); if (obj is DataTable) { ds.Tables.Add(obj as DataTable); return ds; } DataTable dt = new DataTable(); ds.Tables.Add(dt); IEnumerable<object> list = obj as IEnumerable<object>; if (list == null) { var properties = obj.GetType().GetProperties().ToList(); if (properties.Count == 0) return null; properties.ForEach(s => dt.Columns.Add(s.Name, Nullable.GetUnderlyingType(s.PropertyType) ?? s.PropertyType)); var row = dt.NewRow(); properties.ForEach(s => row[s.Name] = s.GetValue(obj, null) ?? DBNull.Value); dt.Rows.Add(row); } else { try { var properties = list.ToList()[0].GetType().GetProperties().ToList(); properties.ForEach(s => dt.Columns.Add(s.Name, Nullable.GetUnderlyingType(s.PropertyType) ?? s.PropertyType)); foreach (var i in list) { var row = dt.NewRow(); properties.ForEach(s => row[s.Name] = s.GetValue(i, null) ?? DBNull.Value); dt.Rows.Add(row); } } catch (Exception) { return null; } } return ds; }