Posted at

LINQ

More than 1 year has passed since last update.

AKB48 53rdシングル 世界選抜総選挙 × SHOWROOM

https://www.showroom-live.com/event/akb48_sousenkyo_53rd

のイベント結果を使い、LINQを勉強してみた。


ランキングの読込

string path = @"総選挙6-15.txt";

var sjisEnc = Encoding.GetEncoding("Shift_JIS");
var texts = File.ReadAllLines(path, sjisEnc);

var members = new List<Member>();
var ranking = new Ranking();

foreach (var text in texts)
{
Match match = Regex.Match(text, @"^(\d+)位\s(\S+)\s(\S+)\s?[(|(](.+)[)|)](.+)\spt$");

if (match.Success)
{
int id = Unique.New(members.Select(m => m.Id));
Member member = new Member()
{
Id = id,
FirstName = match.Groups[3].Value,
LastName = match.Groups[2].Value,
TeamName = match.Groups[4].Value,
};

if (!members.Any(m => (m.FirstName == member.FirstName)
&& (m.LastName == member.LastName) && (m.TeamName == member.TeamName))){
members.Add(member);
int.TryParse(match.Groups[5].Value, out int point);
ranking.Dictionary.Add(id, point);
}
}
}


グルーピング


GroupBy

チーム別に名前を出力する。

```csharp

var team = members.GroupBy(m => m.TeamName);

// team: IEnumerable>

foreach(var t in team)

{

System.Diagnostics.Debug.WriteLine(t.Key);

foreach (var m in t)

{

System.Diagnostics.Debug.WriteLine(m.LastName + " " + m.FirstName);

}

}

```


ToLookup

チーム別にグルーピングし、STU48に所属するメンバーだけを出力する。

csharp

// lookup: ILookup<string ,member>

var lookup = members.ToLookup(m => m.TeamName);

var stu = lookup["STU48"];

foreach(var s in stu)

{

System.Diagnostics.Debug.WriteLine(s.LastName + " " + s.FirstName);

}


結合


Join

var rankInMembers = members.Join(ranking.Dictionary,

m => m.Id,
d => d.Key,
(m, d) => new { Id = m.Id, Name = m.LastName + " " + m.FirstName, SR_Point = d.Value });
foreach(var r in rankInMembers)
{
System.Diagnostics.Debug.WriteLine(r.Name + " " + r.SR_Point);
}