.Net(VB,C#) LINQ で重複のないデータを抽出する

LINQを使用して、リストから重複のないデータを抽出します。

テスト用の高級果物クラスです。
【C#】
private class Fruit
{
    public string Name { get; set; }
    public string Rank { get; set; }
    public decimal Price { get; set; }
}
【VB】
Private Class Fruit
    Public Property Name As String
    Public Property Rank As String
    Public Property Price As Decimal
End Class
テストデータを作成します。
【C#】
var fruits = new List<Fruit>()
                {
                    new Fruit(){Name = "りんご", Rank = "A" , Price = 1000 },
                    new Fruit(){Name = "みかん", Rank = "A" , Price = 600 },
                    new Fruit(){Name = "ぶどう", Rank = "B" , Price = 1200 },
                    new Fruit(){Name = "りんご", Rank = "B" , Price = 800 },
                    new Fruit(){Name = "みかん", Rank = "A" , Price = 500 }
                };
【VB】
Dim fruits = New List(Of Fruit)() From
            {
                New Fruit() With {.Name = "りんご", .Rank = "A", .Price = 1000},
                New Fruit() With {.Name = "みかん", .Rank = "A", .Price = 600},
                New Fruit() With {.Name = "ぶどう", .Rank = "B", .Price = 1200},
                New Fruit() With {.Name = "りんご", .Rank = "B", .Price = 800},
                New Fruit() With {.Name = "みかん", .Rank = "A", .Price = 500}
            }
果物名で重複のないデータを抽出します。
【C#】
var nameList = fruits.Select(itm => itm.Name).Distinct();
//--出力--
//りんご
//みかん
//ぶどう
nameList.ToList().ForEach(itm => { Console.WriteLine(itm); });
【VB】
 Dim nameList = fruits.Select(Function(itm) itm.Name).Distinct()
'--出力--
' りんご
' みかん
' ぶどう
nameList.ToList().ForEach(Sub(itm) Console.WriteLine(itm))
果物名とランクで重複のないデータを抽出します。
【C#】
var nameRankList = fruits.Select(itm => new { itm.Name, itm.Rank }).Distinct();
//--出力--
// りんご A
// みかん A
// ぶどう B
// りんご B
nameRankList.ToList().ForEach(itm =>
 { Console.WriteLine(string.Format("{0} {1}", itm.Name, itm.Rank)); });
【VB】
VBでは匿名クラスをキー項目にしたい場合、キーにしたい各プロパティの前にKeyキーワードを付けます。
Dim nameRankList = fruits.Select(Function(itm) New With {Key itm.Name, Key itm.Rank}).Distinct()
'--出力--
' りんご A
' みかん A
' ぶどう B
' りんご B
nameRankList.ToList().ForEach(Sub(itm) _
     Console.WriteLine(String.Format("{0} {1}", itm.Name, itm.Rank)))

他にもGroupByして、各グループの先頭1件目を抽出する方法もあります。
【C#】
var nameRankList = fruits.GroupBy(itm => new { itm.Name, itm.Rank })
                    .Select(grp => grp.First());
//--出力--
// りんご A
// みかん A
// ぶどう B
// りんご B
nameRankList.ToList().ForEach(itm =>
                { Console.WriteLine(string.Format("{0} {1}", itm.Name, itm.Rank)); });
【VB】
VBで匿名クラスのプロパティをキー項目にしたい場合、キーにしたい各プロパティの前にKeyキーワードを付けます。
'重複のない名称&ランク
Dim nameRankList = fruits.GroupBy(Function(itm) New With {Key itm.Name, Key itm.Rank}) _
                        .Select(Function(grp) grp.First())
'--出力--
' りんご A
' みかん A
' ぶどう B
' りんご B
nameRankList.ToList().ForEach(Sub(itm) _
     Console.WriteLine(String.Format("{0} {1}", itm.Name, itm.Rank)))

0 件のコメント: