0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[C#]配列二つを受け取って特定の要素のみが一致するものを返すLINQ

0
Last updated at Posted at 2017-06-29

どゆこと

※ほぼ自分用の覚書になります
言葉にしづらいのでこんなタイトルになりました
正確には以下のとおりです

  • とあるクラスUserがあり、Userは名前とIDを持っている
  • DBから全ユーザー一覧を取得してList<User>を作成する
  • とある箇所で一部のユーザーIDのみを列挙したリストList<int>を取得する
  • IDリストList<int>に列挙されたIDを持つUserList<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)
0
3
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?