I am having difficulties formatting the title of this question. But I think an example will make things clearer.
I have the following list containing a variable amount of other lists which contains a variable amount of 'a' objects.
[
[ a, a, a, a],
[ a, a, a],
[ a, a, a],
[ a, a, a, a],
[ a, a, a],
[ a, a, a, a],
[ a, a, a]
]
in which 'a' represents an instance of the class:
class a {
public int Number { get; set; }
public SomeClass SomeClass { get; set; }
}
Basically what I want is create a list of SomeClass
objects when Number
is equal to 1.
I've achieved this using foreach loops but I'd like to achieve this using Linq.
Pseudocode code using foreach loops:
List<SomeObject> someObjectsList = new List<SomeObject>();
// list is the list which contains lists of 'a' objects described above in the question
foreach (var listOfAObjects in list)
{
var listThatCompliesWithWhereClause = listOfAObjects.Where(x => x.Number == 1);
foreach (var a in listThatCompliesWithWhereClause)
{
someObjectsList.Add(a.SomeObject);
}
}
// someObjectsList is now filled with what I need
How could I solve this with Linq?
Also, suggestions for a better title are also welcome.
Try
list.SelectMany(it => it).Where(it => it.Number == 1).Select(it => it.SomeClass)
You're accessing list
twice which I believe is a typo.
The exact equivalent of your approach using LINQ is as follows:
var resultSet =
list.SelectMany(listOfAObjects => listOfAObjects.Where(x => x.Volgnummer == 1))
.Select(a => a.SomeObject)
.ToList();
This uses SelectMany
to collapse all the nested IEnumerable<IEnumerable<T>>
to a IEnumerable<T>
where T
is the type of elements contained in listOfAObjects
which we then project to a IEnumerable<R>
with the Select
clause and finally we then accumulate the elements into a List.
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