Sothun Thay
Sothun Thay

Reputation: 41

How to write C# method to return a List<T>?

this is an on-going exercise from my previous question "List joins DataTable".

I want to write a method that return a List. In my example below, the intellisence does not recognize "return query;".

Can you please advise what I am doing wrong here?


public List<CodeName> CodeNameList()
{
    List<CodeName> lst = new List<CodeName>();
    lst.Add(new CodeName { code = "1", name = "x" });
    lst.Add(new CodeName { code = "2", name = "y" });
    lst.Add(new CodeName { code = "3", name = "z" });

    DataTable dt = new DataTable();
    dt.Columns.Add("code", typeof(string));
    dt.Columns.Add("value", typeof(string));
    dt.Rows.Add("3", "a");
    dt.Rows.Add("4", "b");
    dt.Rows.Add("5", "c");

    var query = (from l in lst
                join d in dt.AsEnumerable() on l.code equals d.Field<string>("code")
                select new { l.code, l.name}).ToList();

    return query;
}

public class CodeName
{
    public string code { get; set; }
    public string name { get; set; }
}

Upvotes: 1

Views: 134

Answers (2)

Avner Shahar-Kashtan
Avner Shahar-Kashtan

Reputation: 14700

There's a reason the var keyword was introduced alongside LINQ. It's because a LINQ query will often return an anonymous type - a type that's created ad-hoc as part of your query, that isn't an explicitly defined type, and thus, var allows you to specify a variable of that type.

This is what happens here. Your LINQ query creates a collection of an anonymous type that has two fields, code and name, that's created ad-hoc in your select statement: select new {l.code, l.name}. So your query variable isn't a a List<CodeName>, but a List<[unprintable anonymous type]>. The fact that the anonymous type is structurally identical to CodeName doesn't matter, because C# is a strictly typed language and wants the types to be the same declared type.

You can easily fix it by creating a new CodeName in your query, instead of the anonymous type, and the Object Initializer syntax even makes it easy:

var query = (from l in lst
            join d in dt.AsEnumerable() on l.code equals d.Field<string>("code")
            select new CodeName { code = l.code, name = l.name}).ToList();

Upvotes: 2

Stefan Wuebbe
Stefan Wuebbe

Reputation: 2159

Your query is a List, but not a List< Codename > - you can modify the "new" part like this:

            var query = (from l in lst
                     join d in dt.AsEnumerable() on l.code equals d.Field<string>("code")
                     select new CodeName { code = l.code, name = l.name }).ToList();

Upvotes: 0

Related Questions