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();
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.
You could use a nested Any() for this check which is available on any Enumerable : bool hasMatch = myStrings. Any(x => parameters. Any(y => y.
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> .
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.
Use GroupBy
.
List<Bar> BarList = FooList.GroupBy(f => f.Id, f => f.Name, (id, names) => new Bar
{
Id = id,
NameList = names.ToList()
}).ToList();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With