列出特定类的重复项

时间:2009-12-08 08:52:35

标签: c# list contains duplicate-removal

我有一个列表List<T> instances

其中T有日期变量和字符串ID。现在我需要列表来删除字符串ID上的重复项,并仅保留最新日期。谁知道怎么做?

我正在考虑创建一个新列表List<T> final并循环实例列表。在循环中检查列表是否包含带有ID的项目,然后添加项目或删除具有较低日期的重复项目。

但是我不知道如何检查类T的变量上的包含。 我是否必须使用lambda表达式执行此操作?或覆盖List的Equals()?忘了怎么做了。有什么帮助吗?

或者更好的想法永远都是欢迎的!

非常感谢

4 个答案:

答案 0 :(得分:4)

正如蒂姆罗宾逊所说:

var instances = new List<Data>() {
    new Data() {
        Name = "Two",
        Date = new DateTime(1998, 1, 1)
    },
    new Data() {
        Name = "Two",
        Date = new DateTime(1997, 1, 1)
    },
    new Data() {
        Name = "One",
        Date = new DateTime(1998, 1, 1)
    },
    new Data() {
        Name = "One",
        Date = new DateTime(1997, 1, 1)
    },
    new Data() {
        Name = "Three",
        Date = new DateTime(1998, 1, 1)
    },
    new Data() {
        Name = "Three",
        Date = new DateTime(1997, 1, 1)
    }
};

var groupedMax = from i in instances
    group i by i.Name into g
    select new Data() {
        Name = g.Key, 
        Date = g.Max(i => i.Date)
    };

public class Data
{
    public string Name { get; set; }
    public DateTime Date { get; set; }
}

答案 1 :(得分:3)

你能使用.NET 3.5吗?这听起来像是字符串ID上的GroupBy,然后是每个分组上的Max以获取最新日期。

答案 2 :(得分:1)

您也可以尝试

public class MyClass
{
  public DateTime dateTime;
  public int ID;
}
private void button1_Click(object sender, EventArgs e)
{
  List<MyClass> list = new List<MyClass>();

  list.Add(new MyClass() { dateTime = new DateTime(2009, 01, 01), ID = 1 });
  list.Add(new MyClass() { dateTime = new DateTime(2009, 02, 01), ID = 1 });
  list.Add(new MyClass() { dateTime = new DateTime(2009, 02, 01), ID = 2 });

  var dd = from d in list
                     group d by d.ID into g
                     let MaxDate = g.Max(u => u.dateTime)
                     select new { g.Key, MaxDate };
 }

答案 3 :(得分:0)

听起来应该

0) create a map that will use the String ID as the key
1) loop thru the list, 
  2) check if there is something already in the map at the map location for ID 
  3) If there is nothing, add the item
  4) If there is something there, update the map with the most recent item, and discard the other item. 

如果这是来自数据库,只需让数据库处理它,而不是通过做其他海报所说的。