How to convert IEnumerable <IEnumerable <T>> to IEnumerable <T>

I have a collection IEnumerable<IEnumerable<T>>that I want to convert to one collection of dimensions. Can this be achieved using a universal extension method? Now I am doing this to achieve this.

List<string> filteredCombinations = new List<string>();

//For each collection in the combinated results collection
foreach (var combinatedValues in combinatedResults)
{
    List<string> subCombinations = new List<string>();
    //For each value in the combination collection
    foreach (var value in combinatedValues)
    {

        if (value > 0)
        {
            subCombinations.Add(value.ToString());
        }
    }
    if (subCombinations.Count > 0)
    {
       filteredCombinations.Add(String.Join(",",subCombinations.ToArray()));
    }
}

If it is not possible to get a general solution, how can I optimize it in an elegant way.

+5
source share
5 answers

Here you go:

var strings = combinedResults.Select
    (
        c => c.Where(i => i > 0)
        .Select(i => i.ToString())
    ).Where(s => s.Any())
    .Select(s => String.Join(",", s.ToArray());
+3
source

You can use the Enumerable.SelectMany extension method for this.

If I read your code correctly, the code for this would be:

var filteredCombinations = combinatedResults.SelectMany(o => o)
    .Where(value => value > 0)
    .Select(v => v.ToString());

. , , . , , :

var filteredCombinations = combinatedResults
     .Where(resultSet => resultSet.Any(value => value > 0)
     .Select(resultSet => String.Join(",",
         resultSet.Where(value => value > 0)
                  .Select(v => v.ToString()).ToArray()));
+18

Enumerable.SelectMany, driis.

, , :

IEnumerable<T> MakeSingleEnumerable<T>(IEnumerable<IEnumerable<T>> combinatedResults)
{
    foreach (var combinatedValues in combinatedResults) {
         foreach (var value in combinatedValues)
              yield return value;
    }
}
+3

. , , drilis.

- . . 1, subCombinations, Linq:

List<string> filteredCombinations = new List<string>();

//For each collection in the combinated results collection
foreach (var combinatedValues in combinatedResults)
{
    var subCombinations = combinatedValues.Where(v => v > 0)
                                          .Select(v => v.ToString())
                                          .ToList();

    if (subCombinations.Count > 0)
       filteredCombinations.Add(string.Join(",",subCombinations.ToArray()));
}

, :

var filteredCombinations = combinatedResults
    .Select(values => values.Where(v => v > 0)
                            .Select(v => v.ToString())
                            .ToArray())
    .Where(a => a.Count > 0)
    .Select(a => string.Join(",", a));
+2
0

All Articles