STORM STORM - 4 days ago 6
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
ProjectServerUrl
. 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
var listP = projects
    .Where(x => (x.ProjectServerUrl != null && x.ProjectServerUrl != ""))
    .ToList();

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

You can simplify this:

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