简体   繁体   中英

IQueryable remove from the collection, best way?

IQueryable<SomeType> collection = GetCollection();
foreach (var c in collection)
{
    //do some complex checking 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.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM