You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何合并两个var类型的LINQ查询结果?附代码示例

Merging Two Anonymous Type Collections in C# LINQ

Hey there! Looking at your two LINQ query results (results and resultsMaxMin), since they’re both collections of anonymous types with identical property names and data types, merging them is straightforward with LINQ’s built-in methods. Here’s how to do it:

Option 1: Combine All Elements (Including Duplicates)

Use Concat() to append all elements from resultsMaxMin to results—this keeps every entry, even if there are duplicates between the two sets:

var mergedAllResults = results.Concat(resultsMaxMin);

Option 2: Combine and Remove Duplicates

If you want to eliminate duplicate entries (where all property values match exactly between an item from results and resultsMaxMin), use Union(). Anonymous types automatically implement value equality, so this works out of the box:

var mergedUniqueResults = results.Union(resultsMaxMin);

Bonus: Chain Additional Operations

You can easily add sorting or filtering after merging, just like with any other LINQ query. For example, to re-sort the merged collection:

var mergedSortedResults = results.Concat(resultsMaxMin)
                                 .OrderBy(x => x.Substation)
                                 .ThenBy(x => x.S6_NAME);

Important Note

This approach only works if the anonymous types from both queries have exactly the same property names and data types. If there’s a mismatch (e.g., ptime is a different type in one set), you’ll need to adjust your queries to align the types first (like casting table1["ptime"] to string in resultsMaxMin to match results).

内容的提问来源于stack exchange,提问作者nnmmss

火山引擎 最新活动