我正在尝试以某种方式获取原始包含客户id和sallerid的列表。是否可以先使用两个选择然后用Union来完成,这有什么捷径吗?代码如下:
public class Model
{
public int CustomerId { get; set; }
public int SallerId { get; set; }
}
var list = new List<Model>
{
new Model(),
new Model()
};
var customerIds = list.Select(model => model.CustomerId);
var sallerIds = list.Select(model => model.SallerId);
var userIds = customerIds.Union(sallerIds);
如何通过一个操作而不是三个操作来获取用户ID
答案 0 :(得分:2)
您可以按照以下步骤在一个管道中进行操作:
var result = list.SelectMany(x => new int[] {x.CustomerId, x.SallerId})
.Distinct();
这实际上将每个对象CustermerId
和SallerId
投影到一个数组中,然后折叠嵌套序列,最后调用Distinct
删除重复项。
答案 1 :(得分:0)
answer from Aomine几乎可以满足您的要求。但是也许另一种方法可以简化您的问题。
如果您不希望Model成为POCO,则只需将方法GetUserIds()添加到Model类:
public List<int> GetUserIds()
{
return new List<int> {CustomerId, SallerId};
}
这样,您可以通过以下方式获取用户ID:
var userIds = list.Select(model => model.GetUserIds());