Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Linq and C#, how could I kinda merge two lists over some criteria?

Tags:

c#

merge

linq

The context


public class Item
{
    public int Index;
    public string Text;
}

...

var items = new List<Item>
{
    new Item {Index=1, Text="Data #1"},
    new Item {Index=8, Text="Data #8"},
    new Item {Index=4, Text="Data #4"},
};

The code


var data = (from item in items
           orderby item.Index
           select item).ToList();

The result


Data[0] = Data #1
Data[1] = Data #4
Data[2] = Data #8

What is wanted


Data[0] = null
Data[1] = Data #1
Data[2] = null
Data[3] = null
Data[4] = Data #4
Data[5] = null
Data[6] = null
Data[7] = null
Data[8] = Data #8

How to achieve this with Linq?

like image 813
Stécy Avatar asked Dec 12 '22 19:12

Stécy


1 Answers

This does what you want:

var result = Enumerable.Range(0, items.Max(x => x.Index) + 1)
                       .Select(i => items.Where(x => x.Index == i)
                                         .Select(x => x.Text)
                                         .SingleOrDefault())
                       .ToList();

Result:

result[0] = null
result[1] = Data #1
result[2] = null
result[3] = null
result[4] = Data #3
result[5] = null
result[6] = null
result[7] = null
result[8] = Data #8

You could improve performance by storing the original data in a Dictionary:

Dictionary<int, string> d = items.ToDictionary(x => x.Index, x => x.Text);
List<string> result = new List<string>();
for (int i = 0; i < d.Keys.Max() + 1; ++i)
{
    string s;
    d.TryGetValue(i, out s);
    result.Add(s);
}
like image 172
Mark Byers Avatar answered Dec 15 '22 08:12

Mark Byers