How to do If statement in Linq Query

I currently have a list containing the following

CountryCode (string)
CountryStr  (string)
RegionStr   (string)
RegionID    (int)
AreaStr     (string)
AreaID      (int)

This is a flattened set of related data (so basically ive search results stored in ive)

The MVC route will only pass one line, which I then need to map to the data at the correct level in heirachy. Therefore, I try to query CountryStr then if it does not produce results in the region, and then in the region; but I need to make this request bit and, for example, ...

 var datURL = (from xs in myList
               //query 1
               where xs.RegionStr == rarREF
               select new
               {
                regionID = xs.RegionId,
                CountryID = xs.CountryCd
               }
               //IF theres no results 
               where xs.AreaStr == rarREF
               select new
               {
                AreaID = xs.AreaID
                regionID = xs.RegionId,
                CountryID = xs.CountryCd
               }             
               ).ToList();

The only way that I see at the moment is to execute each request separately and then check which return values ​​and use this one. I hope there is a smarter, cleaner method.

+3
2

, , - :

var datURL = (from xs in myList
              where xs.RegionStr == rarREF || xs.AreaStr == rarREF
              select new
              {
                AreaID = (xs.AreaStr == rarRef ? xs.AreaID : default(int)),
                RegionID = xs.RegionId,
                CountryID = xs.CountryId
              }
             ).ToList();

, :

var datURL = (from xs in myList
              let isArea = xs.AreaStr == rarREF
              let isRegion = xs.RegionStr == rarREF
              where isRegion || isArea
              select new
              {
                AreaID = (isArea ? (int?)xs.AreaID : null),
                RegionID = xs.RegionId,
                CountryID = xs.CountryId
              }
             ).ToList();

, . int?, , , 0 "no Area".

+4

or? ?

var datURL = (from xs in myList
              where xs.RegionStr == rarREF || xs.AreaStr == rarREF
              select new
              {
               AreaID = xs.AreaStr == rarREF ? xs.AreaID : default(int)
               regionID = xs.RegionId,
               CountryID = xs.CountryCd
              }).ToList();
+1

Source: https://habr.com/ru/post/1713056/


All Articles