Taking objects from list only if not empty

How can I take objects from A only if A is not empty? This is what I am trying, but I realized q != null will always be true as A is a List.

A.Where(q => q.Id == B.Id && q != null)

I need to do the selection in one line only as this is inside a Select Statement.

2 answers

  • answered 2019-01-11 05:40 Douglas Ferreira

    if(A.Count != 0)
        A.Where(q => q.Id == B.Id);


        A.Where(q => q.Id == B.Id);   


    A != null ? A.Where(q => q.Id == B.Id) : return null; //or whatever you want 

  • answered 2019-01-11 05:50 John

    If your list is empty, A.Where(...) will return 0 results. So you're not taking any items from the list if it's empty.

    With regards to your comment about q != null always being true, that's not correct if your list contains reference types as your list can contain null values:

    List<string> A = new List<string>();

    Which means that your clause will fail in this case because your conditions are in the wrong order (the null check should come first):

    A.Where(q => q != null && q.Id == B.Id);

    You can also write this to use a null conditional operator, but note that if B.Id is also null, it will match:

    A.Where(q => q?.Id == B.Id);

    In the example above, calling A.Where(q => q != null && q.Id == B.Id).ToList() will result in a list with 0 items (because the source list doesn't contain any matching elements).