Jmyster Jmyster - 2 months ago 8
C# Question

How to filter In memory Data object with LINQ and "In" statement

I'm trying to fill my DataGrid

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


This is the In Memory object that has data loaded from a different process

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


I tried using this example Linq version of SQL "IN" statement but both the Lambada and LINQ statements are returning null when it should be 100 records.

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

Answer

The problem is that the result is not an ObservableCollection<Goal> but an IEnumerable<Goal>. That is why you are receiving null.

You can do:

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

Using the "x" as "some type" casts the object to that type, and in the case it isn't able to returns null. What you want to do is to create a new ObservableCollecion and pass it the result of the linq query.

Out of MSDN:

The as operator is like a cast operation. However, if the conversion isn't possible, as returns null instead of raising an exception. Consider the following example: