2

在 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 感谢关于多个froms 的提示,但问题是:使用这种语法,你不能有一个动态的froms 的数量 就我而言,我需要与列表from中的项目一样多的 srequestedKeys

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

4 回答 4

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 */ }
于 2012-05-22T16:54:19.527 回答
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,所以如果有人知道更好的解决方案。请评论我或回答我的问题:)

于 2012-05-23T12:45:33.370 回答
1

用户以这种方式可以生成 sql 交叉应用:

    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
于 2014-01-15T09:54:44.467 回答
0
objects
.Join(requestedKeys, o => o.Key, rk => rk, (o, rk) => o)
.SelectMany(o => requestedKeys.Select(k => new {Key = k, Value = o.Value}));
于 2016-11-12T16:38:48.917 回答