[英]What is the return type for a generic list returning an anonymous 2-string type?
I have this function: 我有这个功能:
public static List<string> JoinDataTablesMultipleColumns(DataTable dt1, DataTable dt2, string col1, string col2, string col3) {
var multiJoin = from table1 in dt1.AsEnumerable()
join table2 in dt2.AsEnumerable()
on new {
Col1 = table1.Field < string > (col1),
Col2 = table1.Field < string > (col2),
Col3 = table1.Field < string > (col3),
}
equals new {
Col1 = table2.Field < string > (col1),
Col2 = table2.Field < string > (col2),
Col3 = table2.Field < string > (col3),
}
select new {
SeriesID = table1.Field < string > ("SeriesID"),
CatID = table2.Field < string > ("CatID")
};
//if ( multiJoin != null )
// return multiJoin.ToList();
//else
return null;
}
It works perfectly except that I have the wrong return type. 除了我的返回类型错误外,它的工作原理非常完美。 The only way I can compile and run it is by returning null.
我可以编译和运行它的唯一方法是返回null。 When I stop the debugger before returning and examine
multiJoin.ToList()
in the watch window
, it's exactly what I want: 当我在返回之前停止调试器并在
watch window
检查multiJoin.ToList()
时,这正是我想要的:
But the return type is wrong. 但是返回类型是错误的。 I keep trying
List<string, string>
, but that won't compile. 我一直在尝试
List<string, string>
,但是不会编译。 Probably a simple thing but I am stuck. 可能很简单,但是我被困住了。 Any ideas?
有任何想法吗?
As you note, you're getting a list of anonymous type. 如您所述,您将获得匿名类型的列表。 Anonymous types are not designed to cross out of the methods that create them .
匿名类型的设计不旨在消除创建它们的方法 。 There are ways to make that work, but they are confusing, difficult and arcane.
有多种方法可以使该工作正常进行,但它们令人困惑,困难且不可思议。
Do not attempt to do this with anonymous types. 请勿尝试使用匿名类型执行此操作。 In C# 7, you can use a tuple type and return
List<(string, string)>
, and then do 在C#7中,可以使用元组类型并返回
List<(string, string)>
,然后执行
select (table1.Field<string>("SeriesID"), table2.Field<string>("CatID"))
In other versions of C#, make a nominal pair type and create an instance of it in your select clause. 在其他版本的C#中,建立一个名义对类型并在select子句中创建它的实例。
Instead of attempting returning an anonymous type (you can't declare an anonymous return type for your method), create a named type to hold your data: 与其尝试返回匿名类型(您不能为方法声明匿名返回类型),不如创建一个命名类型来保存数据:
public class Item
{
public string SeriesID { get; set;}
//...
}
and use it instead of the anonymous type that you are currently selecting at the end of your query. 并使用它代替查询末尾当前选择的匿名类型。
...select new Item {
SeriesID = table1.Field < string > ("SeriesID"),
CatID = table2.Field < string > ("CatID")
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.