从List <dynamic>查询具有多个类型对象的数据

时间:2015-08-23 19:53:53

标签: .net linq c#-4.0 dynamic

var student1 = new {name: "abc"};
var student2 = new {name: "efg"}
var department1 = new { name: "science", location= "ny"}
var department2 = new { name: "maths", location= "nj"}
var department3 = new { name: "social", location= "ny"}

List<dynamic> dynamicList = new List<dynamic>();

dynamicList.Add(student1);
dynamicList.Add(student2);
dynamicList.Add(department1);
dynamicList.Add(department2);
dynamicList.Add(department3);

现在我想得到dynamicList中的总对象数,其中location =&#34; ny&#34;

var total = dynamicList.Count(x=> (string)x.location == "ny");

这是抛出异常,因为没有定位。

Udpate:当我的位置属性对象是第一个列表时,相同的LINQ查询有效。

    dynamicList.Add(department1);
    dynamicList.Add(department2);
    dynamicList.Add(department3);
    dynamicList.Add(student1);
    dynamicList.Add(student2);
 var total = dynamicList.Count(x=> (string)x.location == "ny");

这可以解决任何错误。

1 个答案:

答案 0 :(得分:0)

您使用的方法很混乱。起初,您使用的是匿名类型。此外,发明LINQ是为了处理泛型类型,即在编译时应该知道类型参数以获得LINQ的好处。 无论如何,您可以使用匿名类型的专业,其类型由属性名称,类型和顺序决定。因此,

的类型
new { name = "", location= ""}

对象与department个对象的类型相同。

以下是您可以使用的代码:

List<dynamic> dynamicList = new List<dynamic>
{
    new {name = "abc"},
    new {name = "efg"},
    new {name = "science", location= "ny"},
    new {name = "maths", location= "nj"},
    new {name = "social", location= "ny"},
};
var type = (new {name = "", location = ""}).GetType();
var methodInfo = typeof(Enumerable).GetMethod("OfType");
var genericMethod = methodInfo.MakeGenericMethod(type);
var total = (genericMethod.Invoke(null, new [] {dynamicList}) as IEnumerable<dynamic>)
            .Count(f => f.location == "ny");