navig8tr navig8tr - 3 months ago 6
C# Question

Convert List<T> into another List<T> that contains another List<T>

I have a list of Foo:

class Foo {
public int Id { get; set; }
public String Name { get; set; }
}


And I want to convert it to a list Bar:

class Bar {
public int Id { get; set }
public List<String> NameList { get; set; }
}


The data in Foo looks like this:

Id Name
-----------
1 Foo1
1 Foo2
1 Foo3
2 Foo3
2 Foo2
2 Foo1


And I want it to look like this:

Id NameList
----------------
1 Foo1
Foo2
Foo3
2 Foo3
Foo2
Foo1


I'm doing this so it will be easier to display in a Razor rendered Html unordered list.
Also, if there is an easy way to do this without conversion, please let me know.

Ultimately, I will display the Html like this:

<li>1
<ul>
<li>Foo1</li>
<li>Foo2</li>
<li>Foo3</li>
</ul>
</li>
<li>2
<ul>
<li>Foo3</li>
<li>Foo2</li>
<li>Foo1</li>
</ul>
</li>


So far I've tried the following Linq code, but it didn't work

BarList = FooList.Select(x => new Bar() {
Id = x.Id,
NameList = x.Select(y => y.)
}).ToList();

Answer

Use GroupBy.

List<Bar> BarList = FooList.GroupBy(f => f.Id, f => f.Name, (id, names) => new Bar
{
    Id = id,
    NameList = names.ToList()
}).ToList();