Mohammad Hossein Amri
Mohammad Hossein Amri

Reputation: 2005

interface compatible with Linq without a chance of multiple exection

I'm writing a very high amount of computed code that need a huge amount of linq stuff, so basically, a method do some stuff, pass to another method do a lot of other stuff using linq. and this is happening like 10k times.

to minimize the effort I created some extensions method that do the repetitive tasks. you can imagine something along this but more complicated

public static IEnumerable<int> IsBiggerThan2(this IEnumerable<int> input){
    return input.Where(x=> x>2);
}

public static IEnumerable<int> IsMod2(this IEnumerable<int> input){
    return input.Where(x=> x%2==0);
}

public static IEnumerable<int> IsMod3(this IEnumerable<int> input){
    return input.Where(x=> x%3==0);
}

my problem is when I use linq, the output is IEnumerable, this could cause to multiple execution, I also don't want to spam .ToList() at end of everyline.

var firstCalculation = someInput.select(x=> x+1);
var biggerAndMod2 = firstCalculation.IsbiggerThan2().IsMod2();
var biggerAndMod2And3 = firstCalculation.IsbiggerThan2().IsMod2().IsMod3();
var biggerAndMod2Plus1= biggerAndMod2.select(x=> x+1).IsBiggerThan2();

// and go on

after many lines it's becoming quite daunting and I wonder why there is no interface that share some characteristic between List and Enumerable.

I can pass IList<int> to IEnumerable<int> but not the vice versa and I need to cast it to list, I am looking for a workaround that I can accept linq result as my Input without needing to cast it to List

public static IEnumerable<int> IsMod3(this ISomething<int> input){
    return input.Where(x=> x%3);
}

I tried ICollection, IReadonlyList, IList but no luck, all need to cast to List

Update 1:

in describing the problem I made it over simplified, in those extension methods there are similar cases as what I showed with multiple use of the input arguments. in this way either I need to call .ToList on every input variable or before use of every extensions

Upvotes: 1

Views: 59

Answers (1)

Orace
Orace

Reputation: 8359

The experimental Memoize method from MoreLinq may be what you want.

Upvotes: 3

Related Questions