views:

90

answers:

3

How can I create an easy helper method to get an int array from a collection of objects?

The idea would be have a method which receive a collection of "User" class:

public class User { 
    public int UserId {get;set;}
    public string UserName {get;set;}
}

And filter this collection to get an int array of unique UserIds.

List<int> repeatedUserIds = (from item in list 
                             select item.UserId).ToList();
List<int> uniqueUserIds = ((from n in repeatedUserIds 
                             select n).Distinct()).ToList();

Is there a way to create a clever method for this purpose?

A: 
 List<int> uniqueUserIds = (from n in list  
                            select item.UserId).Distinct().ToList(); 
James Curran
+2  A: 

Well, I wouldn't bother with a query expression, personally - but the rest is fine:

List<int> repeatedUserIds = list.Select(item => item.UserId)
                                .ToList();
List<int> uniqueUserIds = repeatedUserIds.Distinct()
                                         .ToList();

If you don't need repeatedUserIds for anything else, don't bother with the intermediate call to ToList():

List<int> uniqueUserIds = list.Select(item => item.UserId)
                              .Distinct()
                              .ToList();

(I generally like putting each operation on a separate line, but of course you don't have to.)

Note that your text asks for an array, but your code has been in terms of List<int>. If you genuinely want an int[] instead of a List<int>, just change the ToList() calls to ToArray().

Jon Skeet
+3  A: 

You could create an extension method:

public int[] GetUniqueIds<T>(this IEnumerable<T> items, Func<T, int> idSelector)
{
    return items.Select(idSelector).Distinct().ToArray();
}

And use it like this:

int[] uniqueUserIds = list.GetUniqueIds(u => u.UserId);
Lee
extesions methods are awesome. I've adapted ToArray() to ToList(), added static keyword and it's working pretty well. Thank you Lee
Junior Mayhé