1

如何创建一个简单的辅助方法来从对象集合中获取 int 数组?

这个想法是有一个接收“用户”类集合的方法:

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

并过滤此集合以获取唯一 UserId 的 int 数组。

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

有没有办法为此目的创建一个聪明的方法?

4

3 回答 3

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);
于 2010-08-09T14:39:03.717 回答
2

好吧,我个人不会打扰查询表达式 - 但其余的都很好:

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

如果您不需要repeatedUserIds其他任何东西,请不要打扰中间调用ToList()

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

(我通常喜欢将每个操作放在单独的行上,但当然你不必这样做。)

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().

于 2010-08-09T14:34:20.707 回答
0
 List<int> uniqueUserIds = (from n in list  
                            select item.UserId).Distinct().ToList(); 
于 2010-08-09T14:34:02.523 回答