LINQ过滤查询词典列表

时间:2016-03-12 16:58:14

标签: c# linq list dictionary dynamic

我有一个通用Linq查询形式的字典列表。每个字典对象都是一个具有属性的类

  

"名称""年龄""地址"

示例:

public student class{
  public string Name {get;set;}  
  public string age {get;set;}
  public string address {get;set;}
  public string property {get;set;}
}

所以我有通用查询形式的学生词典列表。

List<object>listofStudentDictionaries=new list<object>();

listofStudentDictionaries
{
  content.....
  .............has all dictionaries of student class............... like
  all dictionary content goes inside the listofStudentDictionaries.

  Dictionary<string,object>dictionary=new Dictionary<string,object>();
  dictionary.add(Name,david);
  dictionary.add(age,22);
  dictionary.add(address,asfdsdfs);
  Dictionary<string,object>dictionary=new Dictionary<string,object>();
  dictionary.add(Name,rogers);
  dictionary.add(age,20);
  dictionary.add(address,zczxc);
  Dictionary<string,object>dictionary=new Dictionary<string,object>();
  dictionary.add(Name,richard);
  dictionary.add(age,17);
  dictionary.add(address,gfhghfg);
}

IQueryable<T> query=listofStudentDictionaries.AsQueryable();

现在,我将如何根据列名称(如学生姓名或年龄)过滤此查询。

我想返回查询,即student name="david";

的学生实体

我尝试了所有这些,但它没有工作......

query.ToList().Where(x=>((IDictionary<string, object>)x)[Name] == david);

query.ToList().Where(p => (dynamic)p[Name] == david);

我收到此错误

  

无法将类型数组的索引应用于类型T的表达式。

这些都不会返回name = david的实体。

如何使用Linq实现这一目标。请帮忙。

1 个答案:

答案 0 :(得分:-1)

字典不是最好的方式。使用Linq,如下面的代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            student.students = new List<student>() {
                new student() { Name = "david", age = 22,  address = "asfdsdfs"},
                new student() { Name = "rogers", age = 20,  address = "zczxc"},
                new student() { Name = "richard", age = 17,  address = "gfhghfg"}
            };

            List<student> query = student.students.Where(x => x.Name == "david").ToList();
        }
    }
    public class student
    {
        public static List<student> students {get; set;}
        public string Name{get;set;}
        public int age{get;set;}
        public string address{get;set;}
        public string property {get;set;}
    }
}