Tuesday, March 1, 2011

Filtering in LINQ

From the given setup

IEnumerable<int> one = new int[] { 1, 2, 3, 4, 5, 6, 7 };

IEnumerable<int> two = new int[] { 12, 34, 56, 7, 8 };


MySet[] sets
= new MySet[]
{ 
   new MySet{ MySetID =100, MySubSet=new MySubSet{SubSet=new List<int>(one), 
   SubSetID=1212}},

   new MySet{ MySetID =101, MySubSet=new MySubSet{SubSet=new List<int>(two),
   SubSetID=1414}}
};

How can i filter out even numbers from "SubSet"s

 var GetSet = 
     from mysets in sets 
    where (P => mysets.MySubSet.SubSet.FindAll(???? ))
    select mysets;
From stackoverflow
  • Is this what you want? Your question is rather confusingly worded, but I believe you are looking for something like this:

    var query = from mySet in sets
                select new MySet {
                    MySetID = mySet.ID,
                    MySubSet = new MySubSet {
                        SubSet = mySet.MySubSet.SubSet.Where(p => p % 2 == 0).ToList(),
                        SubSetID = mySet.MySubSet.SubSetID
                    }
                };
    

    So I am interpreting your question to mean that you want to filter out the even numbers from MySubSet.SubSet in each instance of MySet.

    : Yes this is what i expected .Thanks.
    : Bit correction you are filtering out odd numbers,i need even numbers,would you mind asking to change p=>p%2!=0 to p=>p%2==0 ?
    Jason : @russeuludana: You said "filter out even numbers." I interpreted this to mean that you wanted to exclude the even numbers; i.e., you only wanted to see the odd numbers. I have made the change that you requested.
    : I am getting Error " Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'System.Collections.Generic.List'. " in select statement.
    Jason : @russeludana: You need to invoke `ToList` as I caught in my last edit but did not point out that I made the change.

0 comments:

Post a Comment