1

私はリストを持っていますList<T> instances

ここで、T には日付変数と文字列 ID があります。ここで、文字列 ID の重複を削除し、最新の日付のみを保持するリストが必要です。誰でも方法を知っていますか?

List<T> final新しいリストを作成し、インスタンス リストをループすることを考えていました。リストに ID のアイテムが含まれているかどうかをチェックするループ内で、アイテムを追加するか、より古い日付の重複アイテムを削除します。

ただし、クラス T の変数に含まれているかどうかを確認する方法がわかりません。ラムダ式でこれを行う必要がありますか? またはリストの 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 に答える