0
votes

I am new to LINQ lambda expression and i have been stuck for a while regarding the below issue. I want to perform a left outer join and want to select the left table not the right table but the below query gives me error when I select the Left table

The "query" is an IQueryable and also the "model2"

enter image description here

 var model = query.GroupJoin(model2,
                    o => o.plu,
                    m => m.plu,
                    (o, m) => new
                    {
                        SmartCoupon = o,
                        Product = m.DefaultIfEmpty(),
                    })
                    .SelectMany
                    (
                        a => a.SmartCoupon
                    );

Below is the Correct query with the right table but i need the left table

var model = query.GroupJoin(model2,
                    o => o.plu,
                    m => m.plu,
                    (o, m) => new
                    {
                        SmartCoupon = o,
                        Product = m.DefaultIfEmpty(),
                    })
                    .SelectMany
                    (
                        a => a.Product 
                    );
1

1 Answers

5
votes

You are misunderstanding SelectMany().

It is used to flatten List inside another List you need Select() here:

.Select(a => a.SmartCoupon);

Suppose you have List<List<string>>`` and you want all string in aList, then you need to useSelectMany()`.

For Example:

var nameList = new List<List<string>>()
                            {
                                new List<string>
                                    {
                                       "Matt","Adam","John","Peter","Owen"
                                    },
                                new List<string>
                                    { 
                                       "Tim","Jim","Andy","Fred","Todd"
                                    }
                            };

now use SelectMany() to get a single IEnumerable<string>, if you use Select it will return IEnumerable<IEnumerable<string>>:

var namesInSingleList = nameList.SelectMany(x => x);

you can see difference between Select and SelectMany in this SO post