1

I have two classes:

public class firstClass
{
    public int Id { get; set; }
    public List<secondClass> Elements { get; set; }
}

public class secondClass
{
    public int Id { get; set; }
    public bool Is{ get; set; }
}

and using of their:

List<firstClass> list = allFirstClassFromDB.Include("Elements");

and then my list contain for example:

list[0] - {Id : 1, Elements : [0] { Id: 1, Is: true }, [1] { Id: 2, Is: true }, [2] { Id: 3, Is: false }
list[1] - {Id : 2, Elements : [0] { Id:4, Is: false }, [1] { Id: 5, Is: true }, [2] { Id: 6, Is: false }
list[2] - {Id : 3, Elements : [0] { Id:7, Is: false } }

So The result which I need is only this location which contain Elements which have Is prop set for true, sth like this:

list[0] - {Id : 1, Elements : [0] { Id: 1, Is: true }, [1] { Id: 2, Is: true } }
list[1] - {Id : 2, Elements : [0] { Id: 5, Is: true } }

It is possible in linq? Any help would be appreciated.

2 Answers 2

4

Here is how you can do it using LINQ:

var filteredList = list
  .Select(
    x => new firstClass {
      Id = x.Id,
      Elements = x.Elements.Where(y => y.Is).ToList()
    }
  )
  .Where(x => x.Elements.Count > 0);
Sign up to request clarification or add additional context in comments.

Comments

1

First, get rid of firstClass which does not have any secondClass.Is true by Where clause, then re-build firstClass just to filter all secondClass.Is true

list.Where(f => f.Elements.Any(s => s.Is))
    .Select(f => new firstClass() {
                                      Id = f.Id,
                                      Elements = f.Elements.Where(s => s.Is)
                                                           .ToList()
    }).ToList();

Comments

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.