0

我正在尝试解决一个复杂的情况,但是我的 SQL 和 LINQ 技能充其量只是中等水平,我不知道如何实现这一点。我可以用多个查询来做到这一点,但我很想知道我是否可以用一个来做到这一点。

Pricing在 SQL 中有一个表。我关心的三个字段是SearchCodeGUIDLocationGUIDClientGUID。Location 和 Client 都可以为空。

执行查询时,我有一个 SearchGUID、一个 StateGUID、一个 CountyGUID 和一个 ClientGUID。以下是我要执行的查询。对于所有这些,我想要 where SearchGUID = SearchGUID。操作顺序如下:

首先,我想检查客户是否有县的价格 - 地点ClientGUID = ClientGUIDLocationGUID = CountyGUID

如果那不存在,我想看看是否只有那个县的记录 - 在哪里LocationGUID = CountyGUID

如果那不存在,我想看看是否有该州的记录-在哪里LocationGUID = StateGUID

最后,如果不存在,我只想要记录 where LocationGUIDandClientGUID为 null 和SearchGUID匹配项。

4

2 回答 2

1

I like Chase's answer but I figured I'd post a more traditional one. Given a lazy list over a large amount of data this is probably faster... but I make no claims since I really have no clue about your actual data model.

  var idMatch = Pricing.Select(p => p.SearchCodeGUID == SearchGUID);

  var countyMatch = idMatch.Select(p => p.LocationGUID == CountyGUID);

  if (countryMatch.Any()) // match one of two first cases
  {
     var clientToo = countyMatch.Select(p => p.ClientGUID == ClientGUID)
                       .FristOrDefault();

     if (clientToo != null)
       return(clientToo);
     else
       return(countyMatch.First());
  }

  var stateMatch = idMatch.Select(p => p.LocationGUID == stateGUID)
                     .FirstOrDefault();

  if (stateMatch != null) 
    return(stateMatch);

  return(idMatch.Select(p => (LocationGUID == null) && (ClientGUID == null))
           .FirstOrDefault());
于 2013-07-06T21:24:08.210 回答
1

一种方法是使用 OrderBy:

IQueryable<Pricing> table = ...
var matches = table.Where(p => p.SearchGUID = searchGUID);
var result = matches.Select(p => new
{
    pricing = p 
    // 0 score if client & county match 
    score = p.ClientGUID == clientGUID && p.LocationGUID == countyGUID 
        ? 0
        // 1 score if just county match
        : p.LocationGUID == countyGUID
            ? 1
            // 2 score if just state match
            : p.LocationGUID == stateGUID
                ? 2
                // 3 score if client & location are null
                : p.ClientGUID == null && p.LocationGUID == null
                    ? 3
                    // 4 score if it missed all conditions
                    : 4
 })
 .Where(t => t.score < 4) // eliminate mismatches
 .OrderBy(t => t.score) // put low scores first
 .Select(t => t.pricing) // if we want to read just the pricing entity, select it
 .FirstOrDefault(); // take the first match, or null if no match was found
于 2013-07-06T20:59:19.330 回答