c# - Linq cast to list<T> -
i have following classes:
public class column { public string name; public string value; } public class columnlist : list<column> {}
then do:
var cols = (from c in othercolumnlist select new column { name = c.name, }).tolist() columnlist;
however returns null. how can cast list?
what you're trying equivalent this:
animal animal = new animal(); dog dog = animal dog;
one possible solution provide constructor takes existing list, , calls base constructor, such as:
public class columnlist : list<column> { public columnlist(ienumerable<column> collection): base(collection) { } }
and build columnlist
existing collection.
var collection = othercolumnlist.select(c => new column { name = c.name }); var columnlist = new columnlist(collection);
you provide extension method make easier:
public static class columnlistextensions { public static tocolumnlist(this ienumerable<column> collection) { return new columnlist(collection); } } var cols = othercolumnlist.select(c => new column { name = c.name }) .tocolumnlist();
Comments
Post a Comment