A lot of things are wrong here. I am guessing you are quite new to c#. I will try to explain as much as possible -
First,
var customList = await db.MyDbTable
.Select(x => new { x.Id, x.ParentId, x.Title })
.ToListAsync();
customList
is not a collection of <int, int, string>
. The syntax -
x => new { x.Id, x.ParentId, x.Title }
means, x
is an anonymous object
that has 3 properties named Id
, ParentId
, Title
.
Second,
The syntax used is a shortcut. The actual syntax will give you a much more clear picture -
x => new <anonymous object> { Id = x.Id, ParentId = x.ParentId, Title = x.Title }
Third,
Because of what I mentioned at (second), the type definition of the list is this -
List<object> customList = await db.MyDbTable
.Select(x => new { x.Id, x.ParentId, x.Title })
.ToListAsync();
Which is clearly not List<int, int, string>
and will definitely not work. In fact list does not even support List<int, int, string>
. List only takes one data type (List<>
) not three (List<,,>
). More details here - https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1?view=netframework-4.8
Fourth,
Since the list is of type List<object>
, inside the function, the compiler does not know that the object contains Id
, ParentId
and Title
. There are a lot of approach to fix that, you could use class or dynamic objects. The good approach is the class -
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;
}
or you could use value tuple. Read about them here - https://learn.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;
}
or you could use reflection since you already know that object has the properties. But this type of coding is not recommended and you should avoid. But still I am going to show how to use -
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;
}