Home > Enterprise >  Operate with a linq predicate if the list has elements
Operate with a linq predicate if the list has elements

Time:09-17

My question is , how can i operate with the result of a linq operation just if it has any values:

Simple model class:

public class Model{
    public string property;
    public void someOperation(){}
}

Now a simple main method:

List<Model> list...  //supose it has some model objects.
   
list.Where(x=> x.property=="valueNotInTheList").First().someOperation(); //will be a exception
list.Where(x=> x.property=="valueNotInTheList").FirstOrDefault().someOperation(); //will be a exception

My question is , is there a way like the null operator ? or something to do the operation only if the list contains elements in the same linq operation. In fact i need something like this in only one linq operation:

if(list.Any(x=>x.property=="valueNotInTheList")){
    list.Where(x=> x.property=="valueNotInTheList").First().someOperation()
}

Thanks!

CodePudding user response:

You can try FirstOrDefault which returns default (null in your case) value when condition doesn't meet for any of the items. Then to hold null (do nothing in this case) you can put ?. operator instead of just .:

 list
   .FirstOrDefault(x => x.property == "valueNotInTheList")
  ?.someOperation();
  • Related