Question

If I have variable of type IEnumerable<List<string>> is there a LINQ statement or lambda expression I can apply to it which will combine the lists returning an IEnumerable<string>?

Was it helpful?

Solution

SelectMany - i.e.

        IEnumerable<List<string>> someList = ...;
        IEnumerable<string> all = someList.SelectMany(x => x);

For each item in someList, this then uses the lambda "x => x" to get an IEnumerable<T> for the inner items. In this case, each "x" is a List<T>, which is already IEnumerable<T>.

These are then returned as a contiguous block. Essentially, SelectMany is something like (simplified):

static IEnumerable<TResult> SelectMany<TSource, TResult>(
    this IEnumerable<TSource> source,
    Func<TSource, IEnumerable<TResult>> selector) {

    foreach(TSource item in source) {
      foreach(TResult result in selector(item)) {
        yield return result;
      }
    }
}

Although that is simplified somewhat.

OTHER TIPS

How about

myStrings.SelectMany(x => x)

Not exactly a single method call, but you should be able to write

var concatenated = from list in lists from item in list select item;

Where 'lists' is your IEnumerable<List<string>> and concatenated is of type IEnumerable<string>.

(Technically this is a single method call to SelectMany - it just doesn't look like it was all I meant by the opening statement. Just wanted to clear that up in case anyone got confused or commented - I realised after I'd posted how it could have read).

Make a simple method. No need for LINQ:

IEnumerable<string> GetStrings(IEnumerable<List<string>> lists)
{
   foreach (List<string> list in lists)
   foreach (string item in list)
   {
     yield return item;
   }
 }

Using LINQ expression...

IEnumerable<string> myList = from a in (from b in myBigList
                                        select b)
                             select a;

... works just fine. :-)

b will be an IEnumerable<string> and a will be a string.

Here's another LINQ query comprehension.

IEnumerable<string> myStrings =
  from a in mySource
  from b in a
  select b;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top