Using LINQ to avoid foreach

  • Thread starter Thread starter K Viltersten
  • Start date Start date
K

K Viltersten

I have the following passage working well.

List<T> list1D = new List<T>();
List<List<T>> list2D = new List<List<T>>();
foreach (T item in list1D)
list2D.Add(list1D.Where(
x => x.prop == item.prop
).ToList());

I can't help wondering, though, if it's
possible to re-express the LINQ query in
such a way so we actually don't use the
foreach statement at all.

I'm not saying it's wise, requested nor
readable with the redesign. Just being
curious if it's possible and if so, how.
 
K said:
I have the following passage working well.

List<T> list1D = new List<T>();
List<List<T>> list2D = new List<List<T>>();
foreach (T item in list1D)
list2D.Add(list1D.Where(
x => x.prop == item.prop
).ToList());

I can't help wondering, though, if it's possible to re-express the LINQ
query in
such a way so we actually don't use the
foreach statement at all.

I'm not saying it's wise, requested nor readable with the redesign. Just
being curious if it's possible and if so, how.

I'm not sure what you are after...

If you have items in list1D with the prop values 1,1,2,2,2,3,3,3,4, your
code would produce:

1,1
1,1
2,2,2
2,2,2
2,2,2
3,3,3
3,3,3
3,3,3
4

This would do something similar, but without the duplicates:

List<List<T>> list = (
from x in list1D
group x by x.prop into y
select y.ToList()
).ToList();

i.e.:

1,1
2,2,2
3,3,3
4
 
I have the following passage working well.
If you have items in list1D with the prop values
1,1,2,2,2,3,3,3,4, your code would produce:

<snipped out proof of error>

Ooops, sorry! My bad...

It's supposed to be as follows. The array that we
foreach us through is not supposed to be list1D.

List<T> list1D = new List<T>();
List<List<T>> list2D = new List<List<T>>();
foreach (T item in AllPossibleProps)
list2D.Add(list1D.Where(
x => x.prop == item.prop
).ToList());

And one can, of course, assume that there's
no value of the property prop that isn't
contained in the property AllPossibleProps.
 
How about this:

List<List<T>> list2D = AllPossibleProps.Select(x => list1D.Where(y => x.prop
== y.prop).ToList()).ToList();

James.
 
Back
Top