Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
like image 348
navig8tr Avatar asked Jan 13 '16 02:01

navig8tr


People also ask

How do I convert a list to a different list?

Another approach to copying elements is using the addAll method: List<Integer> copy = new ArrayList<>(); copy. addAll(list); It's important to keep in mind whenever using this method that, as with the constructor, the contents of both lists will reference the same objects.

How do you check if a list contains any item from another list C#?

You could use a nested Any() for this check which is available on any Enumerable : bool hasMatch = myStrings. Any(x => parameters. Any(y => y.

How do I convert a list from one type to another in C#?

The recommended approach to convert a list of one type to another type is using the List<T>. ConvertAll() method. It returns a list of the target type containing the converted elements from the current list. The following example demonstrates how to use the ConvertAll() method to convert List<int> to List<string> .

Can we convert list to object?

In short, to convert an ArrayList to Object array you should: Create a new ArrayList. Populate the arrayList with elements, using add(E e ) API method of ArrayList. Use toArray() API method of ArrayList.


1 Answers

Use GroupBy.

List<Bar> BarList = FooList.GroupBy(f => f.Id, f => f.Name, (id, names) => new Bar
{
    Id = id,
    NameList = names.ToList()
}).ToList();
like image 142
M.kazem Akhgary Avatar answered Oct 25 '22 16:10

M.kazem Akhgary