Click here to Skip to main content
Click here to Skip to main content

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

By , 5 Dec 2008
 

Introduction

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.

Background

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.

Example

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
        uniqueList.Add(e.Current.Value);
    }

    // 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.

History

  • v1.0 12/05/2008

License

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
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionNew Proposalmembergugoxx3 Oct '11 - 4:54 
Right. Most remember Linq offers the ToDictionary, but not many remember the ToLookUp.
 
I propose to go with the following:
 
var result = src.ToLookup(s => s.TheKey)
                .Select(res => res.First())
                .ToList();

AnswerRe: New ProposalmemberStephen Inglish3 Oct '11 - 5:08 
This sounds good now that .NET 4 exists. Great recommendation.
Stephen Inglish
Consultant
Sogeti USA
MCPD: Windows Developer
MCPD: Web Developer
MCPD: Enterprise Developer

GeneralMy vote of 1memberPartenon10 May '10 - 23:26 
Functionality already exists
GeneralRe: My vote of 1memberStephen 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
Consultant
Sogeti USA
MCPD: Windows Developer
MCPD: Web Developer
MCPD: Enterprise Developer

GeneralSuggestionsmembertonyt5 Dec '08 - 15:56 
Ignoring the fact that you can to this using other means, there's one thing that sticks out about your imlementation, which is ordering.
 
List is an ordered list. Hence, the relative order of elements should be preserved in operations like this. Your implementation uses the order of the dictionary keys. If you insist on rolling your own, use the dictionary (or a HashSet to store keys, but built the result from the input list), you can preserve the order like this:
 
 
   HashSet<t> keys = new HashSet<t>();
   List<t> result = new List<t>(inputList.Count);
   foreach( T item in list )
   {
      KEY key = func(item);
      if( keys.Add( key ) )
         result.Add(item);
   }
   resultList.TrimExcess();
 
/pre> </t></t></t></t>

GeneralI give upmembertonyt5 Dec '08 - 16:02 
Three times I tried to post a snippet that uses generics, but the editor refuses to keep the code intact.
 
It's simply astounding that a web site devoted to programming can be this disfynctional.
GeneralRe: I give upmvpColin Angus Mackay6 Dec '08 - 0:02 
tonyt wrote:
It's simply astounding that a web site devoted to programming can be this disfynctional.

 
What, exactly, is dysfunctional? I can show generics perfectly:
 
List<MyType> myList = new List<MyType>();

 

GeneralRe: I give upmembertonyt6 Dec '08 - 15:26 
Had you bothered to eloaborate on how that's done, I would have considered your comment to be constructive.
GeneralRe: I give upmvpColin Angus Mackay7 Dec '08 - 0:37 
Well, it is HTML you're typing in there. The normal rules of HTML apply.
 
Therefore to get a < you type &lt;
> is &gt;
& is &amp;
 
My comment was more aimed at your predisposition to blame others for your failure to understand. Instead of seeking a solution you chose to blame others. Had you sought a solution without blaming others I'd have considered your comment to warrant a solution.
 

GeneralRe: I give upmembertonyt8 Dec '08 - 21:43 
Feel free to misrepresent my comments in any manner you wish.
 
But the fact of the matter is, that I most certainly am blaming others for a problem that should not exist, to begin with.
 
The fact that you choose to be an apologist for party responsible for the problem, doesn't change the facts, it only affects how you choose to misrepresent them.

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

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