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.

1
  • You need to parse your JSON string into a ist of your objects first, then use LINQ's Where method to get the single object you're looking for. Commented Jan 7, 2019 at 4:47

1 Answer 1

1

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")
                });
Sign up to request clarification or add additional context in comments.

1 Comment

It's work. thanks Note: "Students = v.Students.Where(y => y.StyleId == "2").toList()"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.