Lin
Lin

Reputation: 23

Filter IEnumerable Data using Linq on ASP.NET Web API 2

I need to filter my data.but i don't know how to use Linq.

The ClassRoom Model

public class ClassRoom
{
    public int RoomID { get; set; }
    public string Name { get; set; }
    public List<Student> Students { get; set; }
}

The Student Model

public class Student
{
    public int StudentId { get; set; }
    public string Name { get; set; }
    public int StyleId {get;set;}
}

Example JSON DATA

  var json= 

    [
        {
            "RoomID": 1,
            "Name": "A Class",
            "Students": [{
                "StudentId": 1,
                "Name":"Charlie",
                "StyleId":"1"
            },
            {
                "StudentId": 2,
                "Name":"Tom",
                "StyleId":"2"
            }
           ]
        },
        {
            "RoomID": 2,
            "Name": "B Class",
            "Students": [{
                "StudentId": 3,
                "Name":"ALLEN",
                "StyleId":"2"
            },
            {
                "StudentId": 4,
                "Name":"Jeremy",
                "StyleId":"2"
            },
            {
                "StudentId": 5,
                "Name":"Curry",
                "StyleId":"3"
            }
           ]
        }

      ]

If i want get StyleID equals "2", and below is expected a answer.

var json = 
 [
    {
        "RoomID": 1,
        "Name": "A Class",
        "Students": [
        {
            "StudentId": 2,
            "Name":"Tom",
            "StyleId":"2"
        }
       ]
    },
    {
        "RoomID": 2,
        "Name": "B Class",
        "Students": [{
            "StudentId": 3,
            "Name":"ALLEN",
            "StyleId":"2"
        },
        {
            "StudentId": 4,
            "Name":"Jeremy",
            "StyleId":"2"
        }
       ]
    }

  ]

Here is how i filer, but not correct. how can i get expected data?

json.Select( v => v.Students.where( i => i.StyleId == "2") )

thanks.

Upvotes: 2

Views: 53

Answers (1)

Karan
Karan

Reputation: 12619

Try linq query as below.

var result = json.Where(v => v.Students.Any(y => y.StyleId == "2"))
                .Select(v => new ClassRoom() {  
                    RoomID = v.RoomID,
                    Name = v.Name,
                    Students = v.Students.Where(y => y.StyleId == "2")
                });

Upvotes: 1

Related Questions