やり方
LINQ のToDictionary
メソッドを使う。
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApp3
{
internal class Program
{
static void Main(string[] args)
{
var pointCards = new List<PointCard>(){
new PointCard(){UserID=1,CardName="Aカード",Point=10, },
new PointCard(){UserID=2,CardName="Bカード",Point =15, },
new PointCard(){UserID=3,CardName="Cカード",Point =20, },
};
// ListからDictionaryに変換
// 引数が1つならKeyを指定
// 引数が2つならKeyとValueを指定
Dictionary<int, PointCard> pointCardDict
= pointCards.ToDictionary(x => x.UserID);
// ↑と同じ
Dictionary<int, PointCard> pointCardDict2
= pointCards.ToDictionary(x => x.UserID, x => x);
}
}
public class PointCard
{
public int UserID { get; set; }
public string CardName { get; set; }
public int Point { get; set; }
}
}
顧客管理とか、1人のユーザーに対して複数あるものを扱う時に使えそう。
GroupBy
を組み合わせる
@junerさんからコメントいただきましたので追記します。
ありがとうございます!(勉強になります(^^♪)
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApp3
{
internal class Program
{
static void Main(string[] args)
{
var pointCards = new List<PointCard>(){
new PointCard(){UserID=1,CardName="Aカード",Point=10, },
new PointCard(){UserID=2,CardName="Bカード",Point =15, },
new PointCard(){UserID=3,CardName="Cカード",Point =20, },
new PointCard(){UserID=1,CardName="Dカード",Point =10, },
new PointCard(){UserID=1,CardName="Eカード",Point =25, },
new PointCard(){UserID=2,CardName="Fカード",Point =30, },
};
// ユーザー毎にまとめてみた
Dictionary<int, IGrouping<int, PointCard>> pointCardDictEachUser =
pointCards.GroupBy(x => x.UserID).ToDictionary(x => x.Key);
foreach (KeyValuePair<int, IGrouping<int, PointCard>> pair in pointCardDictEachUser)
{
Console.WriteLine(pair.Key);
foreach (var cards in pair.Value)
{
Console.WriteLine(cards.CardName);
}
}
Console.ReadKey();
}
}
public class PointCard
{
public int UserID { get; set; }
public string CardName { get; set; }
public int Point { get; set; }
}
}