Reputation: 3177
Let's say I have a class Dad which has list of kids:
public class Dad
{
public List<Kid> kids = new List<Kid>();;
}
Each of those kids has a toy:
public class Kid
{
public List<string> Toys = new List<string>();
}
and as a sample I have collection of dads:
Dad d1 = new Dad();
Kid k1 = new Kid();
k1.Toys.Add("toy1");
k1.Toys.Add("toy2");
d1.Kids.Add(k1);
List<Dad> dads = new List<Dad> { d1 };
I am trying to understand how to perform LINQ of List of Dads to change each kid's toy name to upper case.
Something like:
var dadsWithKidsWithChangeToysName = dads.Select(dad => dad.Kids.Select(kid => kid.Toys.ForEach(toy => toy.ToUpper())));
Upvotes: 1
Views: 103
Reputation: 4665
If your classes have a constructor accepting an IEnumerable, you could get it like so :
public class Dad
{
public List<Kid> kids = new List<Kid>();
public Dad(IEnumerable<Kid> kids)
{
this.kids = kids.ToList();
}
}
public class Kid
{
public List<string> Toys = new List<string>();
public Kid(IEnumerable<string> toys)
{
Toys = toys.ToList();
}
}
var dads = new List<Dad> {
new Dad(new [] { new Kid(new [] { "a", "b" }) }),
new Dad(new [] { new Kid(new [] { "c", "d" }) }),
};
var dadsWithKidsWithChangeToysName = dads.Select(d => new Dad(d.kids.Select(k => new Kid(k.Toys.Select(t => t.ToUpper())))));
Upvotes: 1
Reputation: 223267
LINQ is for query, It is not for modification. You shouldn't use it for modification. Instead use a simple iteration (foreach/for) etc.
You can use LINQ to create a new List
of Dad
based on your existing list like:
var modifiedDads = dads.Select(d => new Dad()
{
Kids = d.Kids.Select
(
k => new Kid()
{
Toys = k.Toys.Select(t => t != null ? t.ToUpper() : t).ToList()
}
).ToList()
}).ToList();
Upvotes: 3