怎么办如果声明LINQ查询

编程入门 行业动态 更新时间:2024-10-27 22:31:36
本文介绍了怎么办如果声明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查询

本文发布于:2023-07-09 14:54:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1087125.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:声明   LINQ

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!