簡體   English   中英

如何使用LINQ和“ In”語句過濾內存數據對象

[英]How to filter In memory Data object with LINQ and “In” statement

我正在嘗試填充我的DataGrid

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

這是“內存中”對象,具有從其他進程加載的數據

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

我嘗試使用此示例Linq版本的SQL“ IN”語句,但是當應為100條記錄時,lambda和LINQ語句都返回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<Goal>而是IEnumerable<Goal> 這就是為什么您收到null

你可以做:

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

"x" as "some type"會將對象轉換為該類型,並且在這種情況下,它無法返回null 您要做的是創建一個新的ObservableCollecion ,並將其傳遞給linq查詢的結果。

超出MSDN

as運算符就像強制轉換操作。 但是,如果無法進行轉換,則as返回null而不是引發異常。 考慮以下示例:

從一開始,Jmyster並不是與ObservableCollection一起工作的好主意
即使它是從Collection繼承的,它也具有比使用簡單過濾器時所需的樣板要多得多的東西(諸如Notify events之類的東西)

我強烈建議您使用簡單的List進行所有填充,並且僅在算法末尾將它們全部放入ObservableCollection類中。
這種簡單的行為將防止您處理上下文外問題。
希望能有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM