How to do If statement in Linq Query

雨燕双飞 提交于 2019-12-06 01:11:41

It won't be very easy to read, but you could do this in a single pass using something like this:

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();

It might also be easier to read the query if it's rewritten slightly:

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();

If we save the comparison result, we can reuse it later. I also added a cast to int? to show how you could use a nullable value instead of using 0 as your "no Area" value.

Aren't you looking for or operator? Does this not generate the results you want?

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();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!