将包含多个列的 List<> 发送到方法的正确 C# 语法是什么?

Sti*_*ian 0 c#

接收此列表作为参数的方法的正确语法是什么?

var customList = await db.MyDbTable
    .Select(x => new { x.Id, x.ParentId, x.Title })
    .ToListAsync();
MyMethod(customList);
Run Code Online (Sandbox Code Playgroud)

这不起作用...

private void MyMethod(List<int, int, string> inputList)
{
    // process the input list
    return;
}
Run Code Online (Sandbox Code Playgroud)

bra*_*der 7

这里有很多事情是错误的。我猜你对 c# 很陌生。我会尽量解释——

第一的,

var customList = await db.MyDbTable
.Select(x => new { x.Id, x.ParentId, x.Title })
.ToListAsync();
Run Code Online (Sandbox Code Playgroud)

customList不是 的集合<int, int, string>。语法 -

x => new { x.Id, x.ParentId, x.Title }
Run Code Online (Sandbox Code Playgroud)

表示,xanonymous object具有 3 个属性的Id, ParentId, Title

第二,

使用的语法是一种快捷方式。实际的语法会给你一个更清晰的画面 -

x => new <anonymous object> { Id = x.Id, ParentId = x.ParentId, Title = x.Title }
Run Code Online (Sandbox Code Playgroud)

第三,

由于我在(第二)中提到的,列表的类型定义是这样的 -

List<object> customList = await db.MyDbTable
.Select(x => new { x.Id, x.ParentId, x.Title })
.ToListAsync();
Run Code Online (Sandbox Code Playgroud)

这显然不是List<int, int, string>,也绝对不会奏效。事实上 list 甚至不支持List<int, int, string>. List 只采用一种数据类型 ( List<>) 而不是三种 ( List<,,>)。更多细节在这里 - https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1?view=netframework-4.8

第四,

由于列表的类型为List<object>,在函数内部,编译器不知道该对象包含Id,ParentIdTitle。有很多方法可以解决这个问题,您可以使用类或动态对象。好的方法是上课 -

public class Data {
    public int Id {get;set;}
    public int ParentId {get;set;}
    public string Title {get;set;}
}

List<Data> customList = await db.MyDbTable
.Select(x => new Data { Id = x.Id, ParentId = x.ParentId, Title = x.Title })
.ToListAsync();

private void MyMethod(List<Data> inputList)
{
    // process the input list
    return;
}
Run Code Online (Sandbox Code Playgroud)

或者你可以使用值元组。在这里阅读它们 - https://docs.microsoft.com/en-us/dotnet/csharp/tuples -

var customList = await db.MyDbTable
.Select(x => (Id: x.Id, ParentId: x.ParentId, Title: x.Title ))
.ToListAsync();

private void MyMethod(List<(int Id, int ParentId, string Title)> inputList)
{
    //example 
    var item = inputlist.First())
    var id = item.Id;

    // process the input list
    return;
}
Run Code Online (Sandbox Code Playgroud)

或者您可以使用反射,因为您已经知道该对象具有属性。但是不推荐使用这种类型的编码,您应该避免。但我仍然要展示如何使用 -

var customList = await db.MyDbTable
.Select(x => new { x.Id, x.ParentId, x.Title })
.ToListAsync();

private void MyMethod(List<object> inputList)
{
    //example 
    var item = inputlist.First())
    var id = item.GetType().GetProperty("Id").GetValue(item) //but a lot slower and not recommended
    // process the input list
    return;
}
Run Code Online (Sandbox Code Playgroud)