Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert IEnumerable<IEnumerable<T>> to List<string>?

I really don't understand this T thing yet. I need to convert below result to List

private void generateKeywords_Click(object sender, RoutedEventArgs e)
{
   string srText = new TextRange(
     txthtmlsource.Document.ContentStart,
     txthtmlsource.Document.ContentEnd).Text;
   List<string> lstShuffle = srText.Split(' ')
       .Select(p => p.ToString().Trim().Replace("\r\n", ""))
       .ToList<string>();
   lstShuffle = GetPermutations(lstShuffle)
       .Select(pr => pr.ToString())
       .ToList();
}

public static IEnumerable<IEnumerable<T>> GetPermutations<T>(
                                              IEnumerable<T> items)
{
    if (items.Count() > 1)
    {
        return items
          .SelectMany(
             item => GetPermutations(items.Where(i => !i.Equals(item))),
             (item, permutation) => new[] { item }.Concat(permutation));
    }
    else
    {
        return new[] { items };
    }
}

this line below fails because i am not able to convert properly. i mean not error but not string list either

lstShuffle = GetPermutations(lstShuffle).Select(pr => pr.ToString()).ToList();
like image 368
MonsterMMORPG Avatar asked Jun 06 '13 02:06

MonsterMMORPG


2 Answers

For any IEnumerable<IEnumerable<T>> we can simply call SelectMany.

Example:

IEnumerable<IEnumerable<String>> lotsOStrings = new List<List<String>>();
IEnumerable<String> flattened = lotsOStrings.SelectMany(s => s);
like image 139
MgSam Avatar answered Oct 07 '22 16:10

MgSam


Since lstShuffle implements IEnumerable<string>, you can mentally replace T with string: you're calling IEnumerable<IEnumerable<string>> GetPermutations(IEnumerable<string> items).

As Alexi says, SelectMany(x => x) is the easiest way to flatten an IEnumerable<IEnumerable<T>> into an IEnumerable<T>.

like image 24
dahlbyk Avatar answered Oct 07 '22 18:10

dahlbyk