SelectMany Three Levels Deep

前端 未结 3 1724
甜味超标
甜味超标 2021-02-02 12:18

I can flatten the results of a child collection within a collection with SelectMany:

 // a list of Foos, a Foo contains a List of Bars
 var source = new List<         


        
3条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-02 12:29

    Your query is returning all the widget IDs, instead of all the widgets. If you just want widgets, just use:

    var q = source.SelectMany(foo => foo.Bar)
                  .SelectMany(bar => bar.Widget)
                  .ToList();
    

    If that's still giving "the incorrect result" please explain in what way it's the incorrect result. Sample code would be very helpful :)

    EDIT: Okay, if you want the widget IDs, your original code should be fine:

    var q = source.SelectMany(foo => foo.Bar)
                  .SelectMany(bar => bar.Widget)
                  .Select(widget => widget.WidgetId)
                  .ToList();
    

    That could also be written as

    var q = (from foo in source
             from bar in foo.Bar
             from widget in bar.Widget
             select widgetId).ToList();
    

    if you like query expression format.

    This really should work - if it's not working, that suggests there's something wrong with your data.

    We should have checked before - is this just LINQ to Objects, or a fancier provider (e.g. LINQ to SQL)?

提交回复
热议问题