STORM STORM - 9 months ago 45
C# Question

How to get only objects from list where property x is not null in C#

I have a list of projects

List<Project> projects = ProjectRepository.GetProjects(user);

This returns me the users projects. Each projects can have a property called
. I want to get only those projects from List where the object property ProjectServerUrl is not null. I have tried the following line of code, but it returns me always all items:

List<Project> listP = projects.Where(x => (x.ProjectServerUrl != null || x.ProjectServerUrl != "")).ToList();

What is wrong here?

Amy Amy
Answer Source
var listP = projects
    .Where(x => (x.ProjectServerUrl != null && x.ProjectServerUrl != ""))

I think your || needs to be a &&.

You can simplify this:

var listP = projects
    .Where(x => !String.IsNullOrEmpty(x))