Вопрос

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;
Это было полезно?

Решение 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;

Другие советы

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;
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top