怎么办如果声明LINQ查询 [英] How to do If statement in Linq Query

查看:117
本文介绍了怎么办如果声明LINQ查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在有一个包含以下列表

I currently have a list that contains the following

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

这是一个扁平的集联数据(所以基本上是香港专业教育学院存储在加入搜索结果)

This is a flattened set of linked data (so basically the results of a joined search that ive stored)

在MVC路由只通过一根弦,然后我需要匹配的数据,在heirachy合适的水平。 所以,我想查询CountryStr那么,如果它不产生结果的区域,然后区域;但我需要做的查询实例和该位......

The MVC route will only pass one string which I then need to match up to the data at the right level in the heirachy. So I'm trying to query the CountryStr then if it doesn't produce results the region then the area; but I need to do that bit of the query and for instance...

 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 I see of doing this at the moment is running each query separately then checking which returned values and using that one. I'm hoping there's a cleverer, cleaner method.

推荐答案

这不会是很容易阅读,但你可以使用这样的事情在一个单一的传球做到这一点:

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

如果我们保存的比较结果,我们可以在以后重新使用它。我还添加了强制转换为诠释?来展示如何,你可以使用,而不是使用0作为你的无区值的空值。

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.

这篇关于怎么办如果声明LINQ查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆