一个问题是因为您使用的是匿名类型(但也许这没关系,因为您首先尝试使用它们)您实际上无法声明或传递此列表(您如何声明List<SomeAnonymousTypeThatDoesNotHaveAName>
?)
您可以通过利用泛型类型推断和使用泛型和作弊var
:
public List<T> BuildList<T>(params T[] entries)
{
return new List<T>(entries);
}
当您BuildList
再次调用 时,因为它们是匿名类型,您无法显式分配<T>
,但您可以让类型推断处理它!
var list = BuildList(
new { Name = 1, Age = 31 },
new { Name = 2, Age = 31 },
new { Name = 3, Age = 4 },
new { Name = 4, Age = 1 },
new { Name = 5, Age = 1 });
类型推断可以很好地处理匿名类型并构建您的列表!
Console.WriteLine(list.Count); //5
Console.WriteLine(list[0].Name + ", " + list[0].Age); //1, 31
Console.WriteLine(list.GetType().FullName); //System.Collections.Generic.List`1[[<>f__AnonymousType0`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], query_jyattd, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]]
编辑:更好的是做一个扩展方法!
public static class ArrayExtensions
{
public static List<T> MakeAnonymousList<T>(this T[] entries)
{
return new List<T>(entries);
}
}
然后你可以像这样使用它:
var list = new[] {
new { Name = 1, Age = 31 },
new { Name = 2, Age = 31 },
new { Name = 3, Age = 4 },
new { Name = 4, Age = 1 },
new { Name = 5, Age = 1 }}
.MakeAnonymousList();
编辑:很酷的事情是你有一个完整的功能List<T>
,你可以添加/删除/Linq。添加项目必须使用相同的参数和顺序:
list.Add(new { Name = 6, Age = 2 }); //OK
list.Add(new { Age = 2, Name = 6 }); //compile error!
var maxAge = list.Max(person => person.Age);
var oldPerson = list.Where(person => person.Age == maxAge).First();
Console.WriteLine(maxAge); //31
Console.WriteLine(oldPerson.Name + ", " + oldPerson.Age); //1, 31
智能感知也很好用!