I have a list of objects that I want to transform into another list of objects.
The first object looks like this:
private class ObjectOne
{
public string Name { get; set; }
public string Item{ get; set; }
}
And another like this
public class ObjectTwo
{
public string Name { get; set; }
public IEnumerable<string> Items{ get; set; }
}
I would like to write a linq query or lambda expression that can convert a list of ObjectOne data into a list of ObjectTwo data. Each item in the list of ObjectTwo will contain a distinct name from ObjectOne along will an enumeration of all the items associated with that name.
For example the following list of ObjectOne data
"Name One", "Item One"
"Name One", "Item Two"
"Name Two", "Item Three"
would produce the following ObjectTwo list:
"Name One", {"Item One", "Item Two"}
"Name Two", {"Item Three"}
So performance-wise, there's no difference whatsoever between the two. Which one you should use is mostly personal preference, many people prefer lambda expressions because they're shorter and more concise, but personally I prefer the query syntax having worked extensively with SQL.
In some cases LINQ is just as fast if not faster than other methods, but in other cases it can be slower. We work on a project that we converted to linq and the data lookup is faster but the merging of data between two tables is much slower.
As such, lambdas aren't equivalent to LINQ, they're a shorthand syntax for anonymous functions. However, they're a stepping stone towards LINQ. LINQ is, in its essence, a way to filter, transform and manipulate collections using techniques borrowed from functional programming.
Use the GroupBy Linq operator. Then for each grouping, select the Key (the one you used to group it with), and convert the items of each group into a List.
var oneList = new List<ObjectOne>
{
new ObjectOne {Name = "Name One", Item = "Item One"},
new ObjectOne {Name = "Name One", Item = "Item Two"},
new ObjectOne {Name = "Name Two", Item = "Item Three"}
};
var twoList= oneList.GroupBy(x => x.Name)
.Select (x => new ObjectTwo
{
Name = x.Key,
Items = x.Select(t => t.Item)
});
You can achieve this using the group by
LINQ operator:
var obj2List =
from o in list
group o by o.Name into g
select new ObjectTwo() {Name = g.Key, Items = g.Select(x => x.Item)};
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