首页 文章

将两个属性合并为普通列表c#

提问于
浏览
3

我试图以某种方式得到包含customerid和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);

如何通过一次操作而不是三次操作来获取userIds

2 回答

  • 0

    answer from Aomine几乎可以满足您的要求 . 但也许另一种方法可以简化您的问题 .

    如果您不打算将Model作为POCO,那么只需将方法GetUserIds()添加到Model类:

    public List<int> GetUserIds()
    {
        return new List<int> {CustomerId, SallerId};
    }
    

    这样您就可以通过以下方式获取userIds:

    var userIds = list.Select(model => model.GetUserIds());
    
  • 2

    您可以在一个管道中执行以下操作:

    var result = list.SelectMany(x => new int[] {x.CustomerId, x.SallerId})
                     .Distinct();
    

    这实际上将每个对象 CustermerIdSallerId 投影到一个数组中,然后折叠嵌套序列,最后调用 Distinct 以删除重复项 .

相关问题