gpt4 book ai didi

c# - 需要通过 Union() 中的匿名类型显式转换

转载 作者:行者123 更新时间:2023-11-30 15:07:12 25 4
gpt4 key购买 nike

我有 2 个变量/对象,通过这两个函数检索:

private IQueryable<Project> SelectAll_1(...)
{
return query;
}

类项目是:

private int ID;
private string col1;
private string col2;
private string col3;

还有一个:

private IQueryable<Project_test> SelectAll_2(...)
{
return query;
}

其中 POCO 是:

private string ID_inString;
private string col1;
private string col2;
private string col3;

我需要对它们进行合并,

var P2 = SelectAll_2(...);
var P1 = SelectAll_1(...);

var P3 = P2.Union(P1);

但是我得到一个错误,提到:

The type arguments for method 'System.Linq.Queryable.Union(System.Linq.IQueryable, System.Linq.Expressions.Expression>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

我看到有人通过匿名类型解决了这个问题,但我不确定它是如何工作的。有人有什么想法吗?

最佳答案

你不能联合两种不同的类型,除非一个继承自另一个(例如,你可能可能找到 IEnumerable<object>IEnumerable<string> 的联合,尽管这很少有用).

现在在你的情况下,它听起来像 ProjectProject_test如果各种属性具有相同的含义,则实际上应该是一种类型。目前 ID 属性有不同的类型——但这真的有必要或值得吗?如果它们都是具有相同范围的标识符,则将它们存储在相同的表示中是有意义的。如果属性 具有相同的含义,则根本不应该在它们之间形成联合。如果它们确实具有相同的含义,您应该尝试使两个序列使用相同的类型。

可以为此使用匿名类型,方式如下:

var projectedP1 = P1.Select(x => new { x.ID, x.col1, x.col2, x.col3 });
var projectedP2 = P2.Select(x => new { ID = int.Parse(x.ID_inString),
x.col1, x.col2, x.col3 });
var union = projectedP1.Union(projectedP2);

或者您可以只使用现有类型之一:

var projectedP1 = P1.Select(x => new Project_test { 
ID_inString = x.ID.ToString(),
col1 = x.col1,
col2 = x.col2,
col3 = x.col3 });
var union = projectedP1.Union(P2);

这些中哪一个是更好的主意并不是很明显 - 但如果可能的话,我会返回尝试调和这两种类型,在这一点上你无论如何都没有问题。

关于c# - 需要通过 Union() 中的匿名类型显式转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6884900/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com