1

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?

casperOne
  • 73,706
  • 19
  • 184
  • 253
Junior Mayhé
  • 16,144
  • 26
  • 115
  • 161

3 Answers3

3

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
  • 142,018
  • 20
  • 234
  • 287
  • extesions methods are awesome. I've adapted ToArray() to ToList(), added static keyword and it's working pretty well. Thank you Lee – Junior Mayhé Aug 09 '10 at 14:56
2

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
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0
 List<int> uniqueUserIds = (from n in list  
                            select item.UserId).Distinct().ToList(); 
James Curran
  • 101,701
  • 37
  • 181
  • 258