Creating a List from a List Containing Lists Using Linq

I'm having difficulty formatting the title of this question. But I think the example will become clearer.

I have the following list containing a variable number of other lists, which contains a variable amount of 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, a]
]

in which "a" represents an instance of the class:

class a {
    public int Number { get; set; }
    public SomeClass SomeClass { get; set; }
}

Basically, I want to create a list of objects SomeClasswhen Numberequal to 1.

I achieved this using foreach loops, but I would 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 can I solve this problem using Linq?

In addition, suggestions for a better title are welcome.

+4
source share
2 answers

Try

list.SelectMany(it => it).Where(it => it.Number == 1).Select(it => it.SomeClass)
+11

list , , , .

LINQ :

var resultSet  = 
    list.SelectMany(listOfAObjects => listOfAObjects.Where(x => x.Volgnummer == 1))
        .Select(a => a.SomeObject)
        .ToList();

SelectMany, IEnumerable<IEnumerable<T>> IEnumerable<T>, T - , listOfAObjects, IEnumerable<R> Select , , .

+3

Source: https://habr.com/ru/post/1695526/


All Articles