繁体   English   中英

从集合中删除IQueryable,最好的方法?

[英]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

因此,使用该简单的代码,获得结果的最佳方法是什么。 我应该在foreach之前创建一个List并插入要保留的对象,还是可以通过其他方法更好地进行此类操作。

我知道还有其他类似主题的文章,但是我只是觉得自己没有得到我需要的东西。

编辑我尝试了这个

 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;
 });

我尝试了此操作,但在编译时得到了“带有语句主体的lambda表达式无法转换为表达式树”。 我做错了吗?

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

我不明白 您可以传递一个委托,该委托可以指向一个非常复杂的函数(图灵完成),该函数检查是否应丢弃它:

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

如果需要,可以在另一个函数中对其进行重构:

var result = GetCollection.Where(FunctionThatChecksToDiscardOrNot);

如果将其包装到另一个方法中,则可以使用yield return然后对返回的集合进行迭代,如下所示:

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.
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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