我让这个查询起作用了,但是它没有返回我想要的结果。
我收集了以下内容:
List<TransactionRecord> transactionLog;TransactionRecord简化版看起来像这样:
class TransactionRecord {
public string txSetComments;
public string BatchComments;
public string TargetComments;
public string TargetName;
public string TargetValue;
} 并且可以初始化为:
List<TransactionRecord> transactionLog = new List<TransactionRecord>()
{
new TransactionRecord { txSetComments = "txc1",
BatchComments = "bc1",
TargetComments = "tc1",
TargetName = "target1",
TargetValue = "v1" },
new TransactionRecord { txSetComments = "txc1",
BatchComments = "bc1",
TargetComments = "tc1",
TargetName = "target1",
TargetValue = "v2" },
new TransactionRecord { txSetComments = "txc2",
BatchComments = "bc2",
TargetComments = "tc1",
TargetName = "target2",
TargetValue = "v3" },
new TransactionRecord { txSetComments = "txc2",
BatchComments = "bc1",
TargetComments = "tc1",
TargetName = "target2",
TargetValue = "v4" },
new TransactionRecord { txSetComments = "txc1",
BatchComments = "bc3",
TargetComments = "tc1",
TargetName = "target1",
TargetValue = "v5" },
new TransactionRecord { txSetComments = "txc3",
BatchComments = "bc3",
TargetComments = "tc1",
TargetName = "target3",
TargetValue = "v6" }
};以下是到目前为止的查询:
Dictionary<string, Dictionary<string, IEnumerable<TransactionRecord>>> history =
transactionLog.GroupBy(tx => tx.TxSetComments)
.ToDictionary(g => g.Key,
g => g.GroupBy(b => b.BatchComments).ToDictionary(e => e.Key,
e => e.Where(t => t.TargetName == Target)));这是问题所在。如果我在查询中将“目标”设置为"target1",大部分结果与我预期的一样:
txc1
bc1
target1/v1
target1/v2
bc3
target1/v5这是一个很好的开始,但我也得到了:
txc2
txc3添加到列表中,以获得如下所示的完整结果:
txc1
bc1
target1/v1
target1/v2
bc3
target1/v5
txc2
txc3我希望查询只返回顶层组,如果有匹配的“目标”。在上面的示例中,它仍然返回"txc2“和"txc3”作为顶层组,即使它们与"Target“不匹配。
我希望这不会太令人困惑。有什么建议吗?
谢谢!
发布于 2009-07-07 02:23:19
将Where子句复制到GroupBy之外。
var history = transactionLog.Where(record => record.TargetName == "target1")
.GroupBy(tx => tx.txSetComments)
.ToDictionary(
g => g.Key,
g => g.GroupBy(b => b.BatchComments)
.ToDictionary(e => e.Key,
e => e.Where(t => t.TargetName == "target1"));https://stackoverflow.com/questions/1090068
复制相似问题