Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

If there is no result, an error message will appear. (Null or empty problem)

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");
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading