How to avoid method length creep when using LINQ and vars

I'm using vars to capture anonymous types which are selected into from tables in the DB. It's great, I love it. However, since vars cannot be method parameters, this technique promotes the evolution of overly-long methods that cannot be decomposed e.g.

var res1 = (from t1 in dao.t1
            select new { t1.Id, t1.Cost, t1.Size }).ToList();

<do stuff with res1 ...> 

var res2 = (from r1 in res1 where r1.Cost > 100 
         select new { r1.Id, r1.Size }).ToList();

<do stuff with res2 ...> 

var res3 = (from r2 in res2 where r2.Size > 5
             select new { r2.Id }.ToList();

<do stuff with res3 ...>

Now AFAIK I can't decompose these selects into methods due to the vars. But naturally I don't want to create named types for these intermediary variables as that'd be really clunky and bloaty. So I'm stuck with excessively long methods, Right?


If you're using an anonymous type and you find yourself wishing to use it beyond the scope of a single method, then it's time to promote that anonymous type up to a new named type; use that instead of the anonymous class for the information, and then you can freely extract portions of the method out into other methods.

Yes, unless you create your own classes to handle results, or return something different then anonymous types (e.g. Tuple<...>s).

Anonymous Types (C# Programming Guide)

If you must store query results or pass them outside the method boundary, consider using an ordinary named struct or class instead of an anonymous type.

There is also another possibility to get anonymous type out from method with intellisense: use generics and generic type inference. But I don't think it applies to your case.

Need Your Help

nest home simulator -- sample apps


I am looking forward to create a UiMagician binding for NEST users. At present UiMagician have binding for VSCP iot project.

Why is line not being drawn according to x,y settings I pass?

objective-c ios7 nsdate nsdateformatter

I have an app where I draw vertical lines representing appointments. They are not being drawn where I want them drawn. Here is an example of what is currently being drawn: