を使用した別のアプローチを次に示しList.BinarySearch
ます。
サンプルデータ:
var list1 = new List<int>() { 1, 2, 3, 4 };
var list2 = new List<int>() { 2, 3, 5, 6, 7, 8 };
var list3 = new List<int>() { 3, 4, 5 };
var all = new List<List<int>>() { list1, list2, list3 };
最小/最大およびすべての nullable リストを計算します。
int min = all.Min(l => l.Min());
int max = all.Max(l => l.Max());
// start from smallest number and end with highest, fill all between
int count = max - min + 1;
List<int?> l1Result = new List<int?>(count);
List<int?> l2Result = new List<int?>(count);
List<int?> l3Result = new List<int?>(count);
foreach (int val in Enumerable.Range(min, count))
{
if (list1.BinarySearch(val) >= 0)
l1Result.Add(val);
else
l1Result.Add(new Nullable<int>());
if (list2.BinarySearch(val) >= 0)
l2Result.Add(val);
else
l2Result.Add(new Nullable<int>());
if (list3.BinarySearch(val) >= 0)
l3Result.Add(val);
else
l3Result.Add(new Nullable<int>());
}
出力:
Console.WriteLine(string.Join(",", l1Result.Select(i => !i.HasValue ? "NULL" : i.Value.ToString())));
Console.WriteLine(string.Join(",", l2Result.Select(i => !i.HasValue ? "NULL" : i.Value.ToString())));
Console.WriteLine(string.Join(",", l3Result.Select(i => !i.HasValue ? "NULL" : i.Value.ToString())));
1, 2, 3, 4, NULL, NULL, NULL, NULL
NULL, 2, 3, NULL, 5, 6, 7, 8
NULL, NULL, 3, 4, 5, NULL, NULL, NULL
デモ