どゆこと
※ほぼ自分用の覚書になります
言葉にしづらいのでこんなタイトルになりました
正確には以下のとおりです
- とあるクラス
Userがあり、Userは名前とIDを持っている - DBから全ユーザー一覧を取得して
List<User>を作成する - とある箇所で一部のユーザーIDのみを列挙したリスト
List<int>を取得する - IDリスト
List<int>に列挙されたIDを持つUserをList<User>で取得したい
言葉にするとすごいわかりづらいなぁ…
こういうこと
LINQ.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
List<int> IDList = new List<int> { 1, 3, 5, 7 };
//今回はDB用意するのは面倒なので適当にユーザーデータを作成する
List<User> UserList = new List<User>
{ new User { ID = 0, Name = "ID0" },
new User { ID = 1, Name = "ID1" },
new User { ID = 2, Name = "ID2" },
new User { ID = 3, Name = "ID3" },
new User { ID = 4, Name = "ID4" },
new User { ID = 5, Name = "ID5" },
new User { ID = 6, Name = "ID6" },
new User { ID = 7, Name = "ID7" } };
//IDListにあるIDを持つUser一覧を取得する
foreach (var item in UserList.Where(x => IDList.Contains(x.ID)))
{
Console.WriteLine(item.Name);
//result -> ID1, ID3, ID5, ID7
}
Console.ReadKey();
}
}
class User
{
public int ID { get; set; }
public string Name { get; set; }
}
なんでこんな単純なLINQが思いつかなかったのか…
普段Where(x => x.ID == ほにゃらら)という書き方ばかりしていたので
Where(x => [boolが返る式なら何でもOK])という基本ルールをすっかりと忘れていました
@kiichi54321提案 : ListではなくHashSetを使うことでパフォーマンス向上させることが出来ます
HashSet<int> IDList = new HashSet<int> { 1, 3, 5, 7 };
@yuba さんに別解を提示していただきました、コチラもかなり有用です
UserList.Join(IDList, u => u.ID, id => id, (u, id) => u)