If there is no result, I want an error message to appear, but I could not do it. Any ideas?
otomobil.Add(new Markalar { Marka = "Skoda", Model = "Fabia" });
otomobil.Add(new Markalar { Marka = "Opel", Model = "Astra" });
otomobil.Add(new Markalar { Marka = "Opel", Model = "Vectra" });
otomobil.Add(new Markalar { Marka = "Skoda", Model = "Octavia" });
otomobil.Add(new Markalar { Marka = "BMW", Model = "i5" });
otomobil.Add(new Markalar { Marka = "Audi", Model = "A8" });
Console.WriteLine("Type the brand you want to search:");
string otomarka = Console.ReadLine();
var araba = otomobil.Where(p => p.Marka == otomarka);
foreach (var arac in araba)
{
Console.WriteLine(arac.Model);
if (arac == null)
Console.WriteLine("There were no results");
}
CodePudding user response:
Well, you should check if query's result is empty; we can do it with a help of .DefaultIfEmpty():
var araba = otomobil
.Where(p => p.Marka == otomarka)
.DefaultIfEmpty(); // single null if Where returns empty enumerable
foreach (var arac in araba) {
// if we have null, then we have no result
if (arac == null) {
Console.WriteLine("There were no results");
break;
}
Console.WriteLine(arac.Model);
}