1

我有一个清单List<T> instances

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

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

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

或者更好的想法总是欢迎当然!

非常感谢

4

4 回答 4

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; }
}
于 2009-12-08T09:19:48.303 回答
3

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

于 2009-12-08T08:58:02.533 回答
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 };
 }
于 2009-12-08T09:36:13.317 回答
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. 

如果这是从数据库中出来的,那就让数据库来处理它,而不是按照其他张贴者所说的去做。

于 2009-12-08T09:08:24.943 回答