Question

If list.Find() retuns null.code returning exception. is there a better way to do it. It is in reference to my previous post .

Link : Linq query returning null when trying to pass a column value from list object

ProcessName = Process().Find(x => x.ProcessID == p.ProcessID).ProcessName ?? String.Empty;
Was it helpful?

Solution 2

It's because you are trying to access .ProcessName when .Find() doesn't have anything to return:

Try this:

var matchingProcess = Process().Find(x => x.ProcessID == p.ProcessID);

ProcessName = matchingProcess ? matchingProcess.ProcessName : string.Empty;

OTHER TIPS

Coalesce the results of Find. If Find returns null (i.e. your ProcessID wasn't found) then you will coalesce the null to an object of anonymous type with a single string property ProcessName. Then either your Process object or the object using the anonymous type will both have the ProcessName property and you can use it in your LINQ select from the original question.

ProcessName = (Process().Find(x => x.ProcessID == p.ProcessID) ?? new { ProcessName = "<unknown>" }).ProcessName;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top