LoginSignup
2
2

More than 5 years have passed since last update.

個数の異なる二つのリストをカンマ区切りで縦に結合する

Posted at

個数の異なる二つのリストデータをカンマで区切って縦に並べたいことがあると思います。
そんなときは、以下のようにLINQを使うとうまくまとまります。


var list1 = new string[] { "a", "b", "c", "d", "e" };
var list2 = new string[] { "A", "B", "C" };

//list1.Length >= list2.Lengthとする
var query = from x in list1.Select((item, index) => new { item, index })
            join y in list2.Select((item, index) => new { item, index }) on x.index equals y.index into z
            from a in z.DefaultIfEmpty(new { item = "", index = -1 })
            select x.item + "," + ((a.index != -1) ? a.item : "---");

foreach(var line in query) {
    Console.WriteLine(line);
}

結果は以下のようになります。

a,A
b,B
c,C
d,---
e,---
2
2
0

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
2
2