交叉应用 - LINQ到对象

时间:2012-05-22 16:06:35

标签: c# linq linq-to-objects cross-apply

在T-SQL中,您可以使用CROSS APPLY从语句中获取表格左右之间的所有可能变体。现在我在C#中遇到以下情况,我希望有一种方法可以使用LINQ-to-Objects解决我的问题。

我有一个包含TestData个对象的列表(如下所示),类似于KeyValuePair<string, object>对象(只有一个Key和一个Value属性): 密钥可以是一切,可以有多个具有相同密钥的对象。

IList<KeyValuePair<String, Object>> objects;
// Content of list
// # | Key  | Value
// 1 | "A"  | 1
// 2 | "A"  | 2
// 3 | "A"  | 3
// 4 | "B"  | 4
// 5 | "B"  | 5
// 6 | "C"  | 6
// 7 | "D"  | 7
// 8 | "D"  | 8

我还有一个请求密钥列表:

IList<String> requestedKeys = new List<string>() { "A", "D" };

现在我想在requestedKeys列表中的键之间拥有KeyValuePair对象的所有可能组合。

IList<IList<KeyValuePair<String, Object>>> result = ...
// Content of 'result' will be in this example 6 lists with each 2 KeyValuePair objects
// #  | "A" | "D" | (If there are more in the requestedKey list then there are more KeyValuePair items in the innerlist.)
// 1  |  1  |  7  |
// 2  |  2  |  7  |
// 3  |  3  |  7  |
// 4  |  1  |  8  |
// 5  |  2  |  8  |
// 6  |  3  |  8  |

是否可以使用LINQ-to-Objects解决我的问题。如果没有,你能不能告诉我最有效的方法来构建它。


编辑1:
更清楚地说明结果应该是什么:
我想要一个LINQ-to-Objects查询,如下所示:
@Joanna感谢有关多个from的提示,但问题是:使用此语法,您无法拥有动态数量的from。在我的情况下,我需要from列表

中的项目requestedKeys
var result =    
   from listA in objects.Where(m => m.Key == "A")
   from listD in objects.Where(m => m.Key == "D")
   // from .....
   // from .....
   // overhere as many froms as items in 'requestedKeys' list   
select new [] { listA, listD /*, All other lists */ }

4 个答案:

答案 0 :(得分:3)

这些方面应该有效:

var filtered = objects
        .Where(o => requestedKeys.Contains(o.Key));

var crossJoined = from el1 in filtered
                    from el2 in filtered
                    select new [] {el1, el2};

通过链接多个from子句来实现交叉连接。

修改

在这种情况下,我想不出比你在编辑中开始的更简单的方法。唯一缺少的是选择值:

var result =    
   from listA in objects.Where(m => m.Key == "A").Select(m => m.Value)
   from listD in objects.Where(m => m.Key == "D").Select(m => m.Value)
   // from .....
   // from .....
   // overhere as many froms as items in 'requestedKeys' list  
select new [] { listA, listD /*, All other lists */ }

答案 1 :(得分:1)

我自己找到了解决方案:

这是LINQ中非常复杂的连接,因为requestKeys列表中的每个项都需要额外的交叉连接。关于给定的示例列表,结果应为objects.Count(m => m.Key == "A") * objects.Count(m => m.Key == "D")(结果为3 * 2 = 6)。列表中的每个额外项目都会导致整个结果集的额外乘积。

所以这就是结果:

// The result list
IEnumerable<IList<KeyValuePair<char, int>>> result;

// If there are no requestedKeys there is no result expected
if(requestedKeys.Count() > 0)
{
    // Loop through all request keys to cross join them together
    foreach (var key in requestedKeys)
    {
        if (result == null)
        {
            // First time the innerlist List<KeyValuePair<char, int>> will contain 1 item
            // Don't forget to use ToList() otherwise the expression will be executed to late.
            result = objects.Where(m => m.Key == key).Select(m => new List<KeyValuePair<char, int>>() { m }).ToList();
        }
        else
        {
            // Except for the first time the next subresult will be cross joined
            var subresult = objects.Where(m => m.Key == key).Select(m => new List<KeyValuePair<char, int>>() { m });
            result = result.Join(
                subresult,
                l1 => 0, // This and the next parameter does the cross join trick
                l2 => 0, // This and the previous parameter does the cross join trick
                (l1, l2) => l1.Concat(l2).ToList() // Concat both lists which causes previous list plus one new added item
                ).ToList(); // Again don't forget to 'materialize' (I don't know it is called materialization in LINQ-to-Objects 
                            // but it has simular behaviors because the expression needs to be executed right away)
        }
    }           
}
return result;

不幸的是,它不是完全LINQ所以如果有人知道更好的解决方案。请评论我或回答我的问题:)

答案 2 :(得分:1)

用户这种方式可以生成sql cross apply:

    var comments = AppCommentRepository.Where(com => com.iAction > -1 && productIds.Contains(com.sProductId))
            .GroupBy(c => c.sProductId)
            .SelectMany(p => p.OrderByDescending(cc => cc.dAddTime).Take(commentNum)).ToList();

最后,sql是:

    SELECT [t3].[iCommentId], .....FROM (
        SELECT [t0].[sProductId]
        FROM [dbo].[App_Comment] AS [t0]
        WHERE ([t0].[iAction] > -1) --AND ([t0].[sProductId] IN (@p1))
           GROUP BY [t0].[sProductId]
        ) AS [t1]
CROSS APPLY (
    SELECT TOP (2) [t2].[iCommentId],......
    FROM [dbo].[App_Comment] AS [t2]
    WHERE ([t1].[sProductId] = [t2].[sProductId]) AND ([t2].[iAction] > -1)
-- AND ([t2].sProductId] IN (@p1))
    ORDER BY [t2].[dAddTime] DESC
    ) AS [t3]
ORDER BY [t3].sProductId DESC

答案 3 :(得分:0)

objects
.Join(requestedKeys, o => o.Key, rk => rk, (o, rk) => o)
.SelectMany(o => requestedKeys.Select(k => new {Key = k, Value = o.Value}));