使用LinQ从列表中获取不同的列表对象

时间:2014-07-21 11:11:04

标签: c# linq list

我有物品清单。

class Item{
      public int Year { get; set; }
      public int QuarterIndex { get; set; }
}

如何将List转换为不同的List?

来源:

List<Item> items = new List<Item>(){
 new Item(){ Year = 2013, QuarterIndex = 1},
 new Item(){ Year = 2013, QuarterIndex = 2},
 new Item(){ Year = 2013, QuarterIndex = 3},
 new Item(){ Year = 2013, QuarterIndex = 1}
};

结果:

target = new List<Item>(){
 new Item(){ Year = 2013, QuarterIndex = 1},
 new Item(){ Year = 2013, QuarterIndex = 2},
 new Item(){ Year = 2013, QuarterIndex = 3}
};

2 个答案:

答案 0 :(得分:8)

这是一种简单但可能效率较低的方法,无需修改类本身即可使用:

items = items.GroupBy(i => new { i.Year, i.QuarterIndex })
    .Select(g => g.First())
    .ToList();

另一种方法是实现自定义IEqualityComparer<Item>,您可以将其用于Distinct(以及Enumerable类中的其他方法):

public class ItemComparer : IEqualityComparer<Item>
{
    public bool Equals(Item lhs, Item rhs)
    {
        if(lhs == null || rhs == null) return false;
        return lhs.Year == rhs.Year && lhs.QuarterIndex == rhs.QuarterIndex;
    }

    public int GetHashCode(Item item)
    {
        if(item == null) return 0;
        unchecked
        {
            int hash = 23;
            hash = (hash * 31) + item.Year;
            hash = (hash * 31) + item.QuarterIndex;
            return hash;
        }
    }
}

现在可行:

items = items.Distinct(new ItemComparer()).ToList();

如果您可以/想要修改原始课程,可以覆盖Equals + GetHashCode

public class Item
{
    public int Year { get; set; }
    public int QuarterIndex { get; set; }

    public override bool Equals(object otherItem)
    {
        Item other = otherItem as Item;
        if (other == null) return false;
        return this.Equals(other);
    }

    public bool Equals(Item otherItem)
    {
        if(otherItem == null) return false;
        return Year == otherItem.Year && QuarterIndex == otherItem.QuarterIndex;
    }

    public override int GetHashCode()
    {
        unchecked
        {
            int hash = 23;
            hash = (hash * 31) + Year;
            hash = (hash * 31) + QuarterIndex;
            return hash;
        }
    }
}

然后Distinct自动运行&#34;:

items = items.Distinct().ToList();

答案 1 :(得分:0)

此代码可以为您提供帮助,

objlist.Where(w => w.ColumnName != "ColumnValue").GroupBy(g => new { g.Value, g.Name }).
                 Select(s=> new ClassName(s.Key.Value, s.Key.Name)).ToList()

快乐编码:)