如何用Lambda表达式关联多列?需优化仅关联ProcessId的Join查询
How to Join on Both ProcessId and GroupId in LINQ
Got it, let's adjust your LINQ query to join using both ProcessId and GroupId instead of just ProcessId. The fix is straightforward—you just need to use an anonymous type in the key selectors for both collections, so LINQ matches rows where both properties are equal.
Here's your updated query:
return process.Join( pendingProcess, p => new { p.ProcessId, p.GroupId }, // Left key: combines both ProcessId and GroupId pp => new { pp.ProcessId, pp.GroupId }, // Right key: mirrors the left key's structure (p, pp) => new Process { ProcessId = p.ProcessId, GroupId = p.GroupId, Text = p.Text } ).ToList();
Quick Breakdown:
- Instead of passing a single property as the join key, we create an anonymous type that includes both
ProcessIdandGroupIdfor each collection. - LINQ will only match elements where both properties in the anonymous types are identical (property names and data types must match exactly—they’re case-sensitive!).
- This ensures you’re getting matches linked by both the process ID and its associated group ID, not just the process ID alone.
If you ever need to join on more fields later, you can just add additional properties to the anonymous type following the same pattern.
内容的提问来源于stack exchange,提问作者Ronaldo Peixoto
相关产品推荐
相关产品推荐

