How to use async lambda with SelectMany?

This is an extension: public static async Task<IEnumerable<T1>> SelectManyAsync<T, T1>(this IEnumerable<T> enumeration, Func<T, Task<IEnumerable<T1>>> func) { return (await Task.WhenAll(enumeration.Select(func))).SelectMany(s => s); } That allows you to run: var result = await myEnumerable.SelectManyAsync(c => Functions.GetDataAsync(c.Id)); Explanation: you have a list of tasks, each returns Task<IEnumerable<T>>. So you need to fire them all, then await all, and … Read more

How to debug a LINQ Statement

Yes it is indeed possible to pause execution midway through a linq query. Convert your linq to query style using lambda expressions and insert a Select statement that returns itself somewhere after the point in the linq that you want to debug. Some sample code will make it clearer – var query = dataset.Tables[0].AsEnumerable() .Where … Read more

“Nested foreach” vs “lambda/linq query” performance(LINQ-to-Objects) [closed]

Write the clearest code you can, and then benchmark and profile to discover any performance problems. If you do have performance problems, you can experiment with different code to work out whether it’s faster or not (measuring all the time with as realistic data as possible) and then make a judgement call as to whether … Read more

LINQ SelectMany and Where extension method ignoring nulls

survey.QuestionList .Where(l => l.Questions != null) .SelectMany(l => l.Questions) .Where(q => q != null && q.AnswerRows != null) .SelectMany(q => q.AnswerRows); I’d recommend you ensure your collections are never null. null can be a bit of a nuisance if you don’t handle it well. You end up with if (something != null) {} all over … Read more

Sequence contains no elements exception in linq without even using Single

As Dennis Traub has pointed out, the overload of Aggregate you are using throws that exception when the source sequence is empty. The obvious fix is to use the other overload of Aggregate that accepts an initial seed (you want string.Empty), but that would result in a leading comma in the result which you’ll have … Read more

With Entity Framework is it better to use .First() or .Take(1) for “TOP 1”?

From LINQPad: C#: age_Centers.Select(c => c.Id).First(); age_Centers.Select(c => c.Id).FirstOrDefault(); age_Centers.Select(c => c.Id).Take(1).Dump(); SQL: SELECT TOP (1) [t0].[Id] FROM [age_Centers] AS [t0] GO SELECT TOP (1) [t0].[Id] FROM [age_Centers] AS [t0] GO SELECT TOP (1) [t0].[Id] FROM [age_Centers] AS [t0] *Note that Take(1) enumerates and returns an IQueryable.

C# Linq where clause as a variable

You need to assembly an Expression<Func<T, bool>> and pass it to the Where() extension method: Expression<Func<T, bool>> whereClause = a => a.zip == 23456; var x = frSomeList.Where(whereClause); EDIT: If you’re using LINQ to Objects, remove the word Expression to create an ordinary delegate.