Click here to Skip to main content
11,806,590 members (45,204 online)
Click here to Skip to main content

LINQ Extension Method to Return a Unique List Based on a Key

, 5 Dec 2008 CPOL 42.8K 8
Rate this:
Please Sign up or sign in to vote.
LINQ Extension method to return a Unique List based on a key


This article is about a handy LINQ extension method that will take a List<T> and a key selector, and return a unique List<T> based on that key.


I had a need to use an in-code way of refining a List<T> so there was no duplication on a key. I developed this handy LINQ Extension to do it for me.

Using the Code

Use this method on any List<T>. This is an extension method, so it has to be put in a static class.


List<MyClass> classList; 

Assuming classList is populated with values...

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&lt;T&gt; 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

    // return the unique list
    return uniqueList;

Points of Interest  

While LINQ has a .ToDictionary() extension method, if you have a List<T> that contains items that aren't unique, .ToDictionary() will throw an exception indicating that a key already exists in the dictionary.  So I had to write the code above to only add items to the dictionary if they didn't already exist.


  • v1.0 12/05/2008


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Stephen Inglish
Software Developer (Senior) Harland Financial Solutions
United States United States
No Biography provided

You may also be interested in...

Comments and Discussions

QuestionNew Proposal Pin
gugoxx3-Oct-11 4:54
membergugoxx3-Oct-11 4:54 
AnswerRe: New Proposal Pin
Stephen Inglish3-Oct-11 5:08
memberStephen Inglish3-Oct-11 5:08 
GeneralMy vote of 1 Pin
Partenon10-May-10 23:26
memberPartenon10-May-10 23:26 
GeneralRe: My vote of 1 Pin
Stephen Inglish3-Oct-11 5:10
memberStephen Inglish3-Oct-11 5:10 
Prior to 2010-04-12, .NET 4 didn't exist, LINQ was just released, and I couldn't find it elsewhere.

To be helpful, instead of just blasting this as useless, link what functionality you are stating already exists so others who find this article can use it.
Stephen Inglish
Sogeti USA
MCPD: Windows Developer
MCPD: Web Developer
MCPD: Enterprise Developer

GeneralSuggestions Pin
tonyt5-Dec-08 15:56
membertonyt5-Dec-08 15:56 
GeneralI give up Pin
tonyt5-Dec-08 16:02
membertonyt5-Dec-08 16:02 
GeneralRe: I give up Pin
Colin Angus Mackay6-Dec-08 0:02
mvpColin Angus Mackay6-Dec-08 0:02 
GeneralRe: I give up Pin
tonyt6-Dec-08 15:26
membertonyt6-Dec-08 15:26 
GeneralRe: I give up Pin
Colin Angus Mackay7-Dec-08 0:37
mvpColin Angus Mackay7-Dec-08 0:37 
GeneralRe: I give up Pin
tonyt8-Dec-08 21:43
membertonyt8-Dec-08 21:43 
GeneralRe: I give up Pin
Günther M. FOIDL6-Dec-08 2:12
memberGünther M. FOIDL6-Dec-08 2:12 
GeneralRe: I give up Pin
tonyt6-Dec-08 15:27
membertonyt6-Dec-08 15:27 
Answer&lt; and &gt; Pin
TobiasP16-Dec-08 0:25
memberTobiasP16-Dec-08 0:25 
GeneralRe: Suggestions Pin
Günther M. FOIDL6-Dec-08 2:15
memberGünther M. FOIDL6-Dec-08 2:15 
GeneralRe: Suggestions [modified] Pin
tonyt6-Dec-08 15:34
membertonyt6-Dec-08 15:34 
GeneralRe: Suggestions Pin
Günther M. FOIDL7-Dec-08 1:49
memberGünther M. FOIDL7-Dec-08 1:49 
GeneralDistinct and Intersect Pin
Mark Nischalke5-Dec-08 13:50
memberMark Nischalke5-Dec-08 13:50 
GeneralRe: Distinct and Intersect Pin
Günther M. FOIDL6-Dec-08 2:21
memberGünther M. FOIDL6-Dec-08 2:21 
GeneralRe: Distinct and Intersect Pin
Mark Nischalke6-Dec-08 3:30
memberMark Nischalke6-Dec-08 3:30 
GeneralRe: Distinct and Intersect Pin
Günther M. FOIDL6-Dec-08 4:32
memberGünther M. FOIDL6-Dec-08 4:32 
GeneralImprovement [modified] Pin
Günther M. FOIDL5-Dec-08 10:52
memberGünther M. FOIDL5-Dec-08 10:52 
GeneralRe: Improvement Pin
Jean-Paul Mikkers5-Dec-08 12:04
memberJean-Paul Mikkers5-Dec-08 12:04 
GeneralConvert extension from List to IEnumerable&lt;T&gt; Pin
Michael Lee Yohe19-Dec-08 6:13
memberMichael Lee Yohe19-Dec-08 6:13 
GeneralRe: Convert extension from List to IEnumerable<T> Pin
Partenon10-May-10 23:21
memberPartenon10-May-10 23:21 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.151002.1 | Last Updated 5 Dec 2008
Article Copyright 2008 by Stephen Inglish
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid