Reputation: 1385
I have a variable defined as:
List<List<A>> mylist;
where
public class A
{
int b;
int c;
}
I was wondering if there is a lambda expression that can do the following:
for(int i = 0; i < mylist.Count; ++i)
{
for(int j = 0; j < mylist[i].Count; ++j)
{
if(mylist[i][j].b < 10) mylist[i][j].b = 0;
else mylist[i][j].b = 1;
}
}
Upvotes: 0
Views: 3201
Reputation: 15865
Your for loop can be converted to this:
List<List<A>> mylist = new List<List<A>>();
foreach (var t1 in mylist.SelectMany(t => t))
{
t1.b = t1.b < 10 ? 0 : 1;
}
Upvotes: 4
Reputation: 476534
Although there is some discussion about the usability of the List<T>.ForEach
statement, this can perform this task:
mylist.ForEach(x => x.Foreach(y => y.b = (y.b < 10) ? 0 : 1));
Or unroll it in a foreach
loop:
foreach(List<A> la in mylist) {
foreach(A a in la) {
a.b = (a.b < 10) ? 0 : 1;
}
}
The (condition) ? val_true : val_false
is the ternary operator.
Upvotes: 1