6

I have the following:

 foreach (var item in selected)
 {
    var categories = _repo.GetAllDCategories(item);
    var result = from cat in categories
                 select
                     new
                     {
                        label = cat.Name,
                        value = cat.Id
                     };
}

The method GetAllDCategories returns a IEnumerable<T>

How to add result to new IEnumerable object that will contain all the items from result for all the selected items in the loop?

SVI
  • 921
  • 4
  • 11
  • 23

3 Answers3

14

Could you not use Concat?

Something like

        IEnumerable<string> s1 = new List<string>
                                    {
                                        "tada"
                                    };
        IEnumerable<string> s2 = new List<string>
                                    {
                                        "Foo"
                                    };
        s1 = s1.Concat(s2);
Adriaan Stander
  • 162,879
  • 31
  • 289
  • 284
3
var result = selected.Select(item=>_repo.GetAllDCategories(item))
                     .SelectMany(x=>x,(x,cat)=> select new {
                                                   label = cat.Name, 
                                                   value = cat.Id
                                                });
King King
  • 61,710
  • 16
  • 105
  • 130
  • Gave an error `The type arguments for method 'IEnumerable System.Linq.Enumerable.SelectMany (this IEnumerable, Func>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.` I've put the type explicitly but didn't work! – SVI Aug 20 '13 at 08:36
1

Well, I think there is some confusion here,

var result = selected.SelectMany(item => 
    _repo.GetAllDCategories(item).Select(cat =>
        new
        {
            Label = cat.Name,
            Value = cat.Id
        });

seems to me what you want.

You can use SelectMany to "squash" or "flatten" an IEnumerable<IEnumerable<T>> into an IEnumerable<T>.

Its similar to having a function like this

IEnumerable<KeyValuePair<string, int>> GetSelectedCategories(
        IEnumerable<string> selected)
{
    foreach (var item in selected)
    {
        foreach (var category in _repo.GetAllDCategories(item))
        {
            yield return new KeyValuePair<string, int>(
                category.Name,
                category.Id);
        }
    }
}
Jodrell
  • 34,946
  • 5
  • 87
  • 124