Skip to main content
 首页 » 编程设计

c#之无法将两个 linq 结果合并为一个 var

2024年02月06日11jpfss

我有两个 linq 结果,我想将它们合并到一个变量中。我怎样才能做到这一点?

 var xAxisconceptIdsAndName = _analysisResult.Select(x => new { x.ConceptId1, x.ConceptDisplay1 }).Distinct(); 
 var yAxisconceptIdsAndName = _analysisResult.Select(x => new { x.ConceptId2, x.ConceptDisplay2 }).Distinct(); 

xAxisconceptIdsAndName 返回 (1,"a"),yAxisconceptIdsAndName 返回 (2,"b")。我希望它们在一个结果中,例如 (1,"a"),(2,"b") 等。

结果:

方法 - 1:

var conceptIdsAndName = Enumerable.Union(xAxisconceptIdsAndName, yAxisconceptIdsAndName); 

错误:

 The type arguments for method 'System.Linq.Enumerable.Union<TSource>(System.Collections.Generic.IEnumerable<TSource>, System.Collections.Generic.IEnumerable<TSource>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. 

方法 - 2:

var conceptIdsAndName = xAxisconceptIdsAndName.Union(yAxisconceptIdsAndName); 

错误:

 'System.Collections.Generic.IEnumerable<AnonymousType#1>' does not contain a definition for 'Union' and the best extension method overload 'System.Linq.Queryable.Union<TSource>(System.Linq.IQueryable<TSource>, System.Collections.Generic.IEnumerable<TSource>)' has some invalid arguments 
 
 Instance argument: cannot convert from 'System.Collections.Generic.IEnumerable<AnonymousType#1>' to 'System.Linq.IQueryable<AnonymousType#2>' 

有什么建议吗?

请您参考如下方法:

您的匿名类型具有不同的属性,因此是不同的类型。如果您使属性的名称、类型和顺序相同,则将使用相同的类型,从而允许您将它们组合成该匿名类型的单个序列。

var xAxisconceptIdsAndName = _analysisResult.Select(x => new  
    {  
        ConceptId = x.ConceptId1,  
        ConceptDisplay = x.ConceptDisplay1  
    }).Distinct(); 
var yAxisconceptIdsAndName = _analysisResult.Select(x => new  
    {  
        ConceptId = x.ConceptId2,  
        ConceptDisplay = x.ConceptDisplay2  
    }).Distinct(); 
var combined = xAxisconceptIdsAndName.Concat(yAxisconceptIdsAndName);