Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List generation from list containing lists using Linq

Tags:

c#

linq

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.

like image 914
JKL Avatar asked Dec 08 '22 15:12

JKL


2 Answers

Try

list.SelectMany(it => it).Where(it => it.Number == 1).Select(it => it.SomeClass)
like image 57
tchelidze Avatar answered Dec 22 '22 00:12

tchelidze


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.

like image 30
Ousmane D. Avatar answered Dec 21 '22 23:12

Ousmane D.