【问题标题】:How to filter In memory Data object with LINQ and "In" statement如何使用 LINQ 和“In”语句过滤内存数据对象
【发布时间】:2017-02-11 18:31:37
【问题描述】:

我正在尝试填充我的 DataGrid

dgGoals.ItemsSource = GetGoals(new int[] { 1, 2, 3 });

这是从不同进程加载数据的 In Memory 对象

static ObservableCollection<Goal> goals = new ObservableCollection<Goal>();

我尝试使用此示例 Linq version of SQL "IN" statement,但 lambda 和 LINQ 语句在应该是 100 条记录时都返回 null。

public static ObservableCollection<Goal> GetGoals(int[] selectedGoalKey)
{
    //goals has 170 records at this point
    //selectedGoalKey has 3 items (1,2,3)
    //goals has 100 records with Goal_Key of 1,2 or 3

    //Returns null
    return goals.Where(f => selectedGoalKey.Contains(f.Goal_Key)) as ObservableCollection<Goal>;

    //Returns null
    return (from g in _Goals
            where selectedGoalKey.Contains(g.Goal_Key)
            select g) as ObservableCollection<Goal>;
}

编辑已修复,现在可以使用

public static IEnumerable<Goal> GetGoals(int[] selectedGoalKey)
{
    //goals has 170 records at this point
    //selectedGoalKey has 3 items (1,2,3)
    //goals has 100 records with Goal_Key of 1,2 or 3

    //Now returns 100 records
    return goals.Where(f => selectedGoalKey.Contains(f.Goal_Key));

    //Now returns 100 records
    return (from g in _Goals
            where selectedGoalKey.Contains(g.Goal_Key)
            select g);
}

【问题讨论】:

  • 您遇到了什么问题?
  • 你为什么要把它投射到ObservableCollection&lt;Goal&gt;?那是你的问题。而是将 IEnumerable 传递给 ObservableCollection&lt;Goal&gt; 构造函数。
  • 当应为 100 条记录时,Lambada 和 LINQ 语句都返回 null。

标签: c# linq filter


【解决方案1】:

Jmyster 从一开始就不是使用 ObservableCollection 的好主意
即使它继承自 Collection,在处理简单过滤器时,它也有比您需要的更多样板。(诸如通知事件之类的东西等等)

我强烈建议您使用简单的列表进行所有过滤,并且仅在算法结束时将它们全部放入 ObservableCollection 类中。
这种简单的行为会阻止您处理脱离上下文的问题。
希望对您有所帮助。

【讨论】:

  • 好吧,我需要知道目标中的记录何时被修改。除了 Observable Collection 之外,还有其他方法吗?
  • 您仍将使用它,但仅在您的方法结束时使用。
    使用 List 执行所有逻辑。最后将其转换为 ObservableCollection
【解决方案2】:

问题是结果不是ObservableCollection&lt;Goal&gt;,而是IEnumerable&lt;Goal&gt;。这就是您收到null 的原因。

你可以这样做:

return new ObservableCollecion<Goal>
    (goals.Where(f => selectedGoalKey.Contains(f.Goal_Key)));

使用"x" as "some type" 将对象转换为该类型,并且在无法返回null 的情况下。您要做的是创建一个新的 ObservableCollecion 并将 linq 查询的结果传递给它。

MSDN:

as 运算符类似于强制转换操作。但是,如果无法进行转换,则 as 返回 null 而不是引发异常。考虑以下示例:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-10
    • 1970-01-01
    • 2016-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-06
    • 2020-12-24
    相关资源
    最近更新 更多