LINQ 扩展方法,用于基于键返回唯一列表






3.46/5 (5投票s)
LINQ 扩展方法,用于基于键返回唯一列表。
引言
本文介绍了一个实用的 LINQ 扩展方法,它接收一个 List<T>
和一个键选择器,并根据该键返回一个唯一的 List<T>
。
背景
我需要一种在代码中精炼 List<T>
的方法,以确保键没有重复。我开发了这个实用的 LINQ 扩展方法来完成它。
Using the Code
可以将此方法应用于任何 List<T>
。由于这是一个扩展方法,因此必须将其放在一个 static
类中。
示例
List<MyClass> classList;
假设 classList
已经填充了值...
List<MyClass> filteredList = classList.Unique(cl => cl.SomeKeyProperty);
/// <summary>
/// Takes a List of type <typeparamref name="T"/>
/// and a function as the key selector and returns a unique list of type
/// <typeparamref name="T"/>
/// from that list
/// </summary>
/// <typeparam name="KEY">The type of the KEY.</typeparam>
/// <typeparam name="T"></typeparam>
/// <param name="InputList">The input list.</param>
/// <param name="func">The func.</param>
/// <returns></returns>
/// <example><code>List<T> uniqueList =
/// nonUniqueList.Unique(key=>key.ID);</code></example>
public static List<T> Unique<KEY, T>(this List<T> InputList, Func<T, KEY> func)
{
if (func == null)
throw new ArgumentNullException("Key selector function cannot be null");
if (InputList == null)
{ return null; }
if (InputList.Count == 0)
{ return InputList; }
// Convert the inputList to a dictionary based on the key selector provided
Dictionary<KEY, T> uniqueDictionary = new Dictionary<KEY, T>();
InputList.ForEach(item =>
{
// Use the key selector function to retrieve the key
KEY k = func.Invoke(item);
// Check the dictionary for that key
if (!uniqueDictionary.ContainsKey(k))
{
// Add that item to the dictionary
uniqueDictionary.Add(k, item);
}
});
// Get the enumerator of the dictionary
Dictionary<KEY, T>.Enumerator e = uniqueDictionary.GetEnumerator();
List<T> uniqueList = new List<T>();
while (e.MoveNext())
{
// Enumerate through the dictionary keys and pull out
// the values into a unique list
uniqueList.Add(e.Current.Value);
}
// return the unique list
return uniqueList;
}
值得关注的点
虽然 LINQ 具有 .ToDictionary()
扩展方法,但如果 List<T>
包含非唯一项,则 .ToDictionary()
会抛出一个异常,表明字典中已存在该键。因此,我编写了上面的代码,仅在键不存在时才将项添加到字典中。
历史
- v1.0 2008/05/12