开发者

IQueryable remove from the collection, best way?

IQueryable<SomeType> collection = GetCollection();
foreach (var c in collection)
{
    //do some complex check开发者_开发技巧ing that can't be embedded in a query
    //based on results from prev line we want to discard the 'c' object
}

//here I only want the results of collection - the discarded objects

So with that simple code what is the best way to get the results. Should I created a List just before the foreach and insert the objects I want to keep, or is there some other way that would be better to do this type of thing.

I know there are other posts on similar topics but I just don't feel I'm getting what I need out of them.

Edit I tried this

 var collection = GetCollection().Where(s =>
 {
      if (s.property == 1)
      {
           int num= Number(s);
           double avg = Avg(s.x);
           if (num > avg)
               return true;
           else
               return false;
      }
      else return false;
 });

I tried this but was given "A lambda expression with a statement body cannot be converted to an expression tree" on compile. Did I not do something right?


//do some complex checking that can't be embedded in a query

I don't get it. You can pass a delegate which can point to a very complex function (Turing-complete) that checks whether you should discard it or not:

var result = GetCollection().AsEnumerable().Where(c => { 
  // ...
  // process "c"
  // return true if you want it in the collection
             });

If you want, you can refactor it in another function:

var result = GetCollection.Where(FunctionThatChecksToDiscardOrNot);


If you wrap it into another method, you can use yield return and then iterate over the returned collection, like so:

public IEnumerable<SomeType> FindResults(IQueryable<SomeType> collection) {

    foreach (var c in collection)
    {
        if (doComplicatedQuery(c)) {
            yield return c;
        }
    }
}

// elsewhere
foreach (var goodItem in FindResults(GetCollection())) {
   // do stuff.
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜