3

I have a Cache wrapper class that I use, which provides type safety and segmenting and other nice things.

I want to make it prevent me from shooting myself in the foot by caching an un-materialized LINQ query and only accept lists/collections...

Is there a way to detect if an IEnumerable is a LINQ query?

Maybe I'm answering my own question and should throw an exception when T is IEnumerable but not ICollection.

Joe Flateau
  • 1,225
  • 1
  • 20
  • 32
  • I'm not sure if it's just me, but I've never heard the term "un-materialized" LINQ query. Can you please clarify what you are asking? – myermian Jan 24 '13 at 00:36
  • I know this isn't what you asked for, but what if you call `.ToList()` to convert `IEnumerable` to `List`? – Kendall Frey Jan 24 '13 at 00:36
  • 2
    @m-y I believe he's using the term to refer to `IEnumerable` implementations which are streamed, such as most LINQ operations, many `IQueryable` implementations, etc. If you use them multiple times, you end up re-executing the implementation. – Reed Copsey Jan 24 '13 at 00:38
  • @Kendall only problem with that is the extra copying of the list if it's not a query – Joe Flateau Jan 24 '13 at 03:45

1 Answers1

3

I would suggest just wrapping the IEnumerable<T> within your own collection, "materializing" it yourself.

This will provide full safety and more consistency, at the expense of potentially generating another collection instance and copying the references over.

You could always do a check for ICollection<T> and not regenerate, or similar, but there are still advantages to copying the contents into your own list. One major one is that you then control the one and only instance of the collection - you don't have to worry about another object adding or removing items (which may or may not be an issue, but is likely problematic for segmenting).

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373