Access property in lambda expression from string when using LINQ

后端 未结 4 1002
渐次进展
渐次进展 2021-01-03 04:40

How can I do something like this:

var result = db.MyTable.Where(x => x.\"MyProperty\" == \"Test\" );

As you can see I want to access \"MyProperty\" but

4条回答
  •  伪装坚强ぢ
    2021-01-03 05:04

    You can use reflection to get it unless you are querying a database directly using LINQ to SQL.

    Here is a sample of how to get property info using reflection:

    class Program
    {
        class Person
        {
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public byte Age { get; set; }
            public override string ToString()
            {
                return string.Format("{0}, {1} ({2})", LastName, FirstName, Age);
            }
        }
    
        static void Main(string[] args)
        {
            Person p1 = new Person() { FirstName = "Bill", LastName = "Johnson", Age = 34 };
            Person p2 = new Person() { FirstName = "Sally", LastName = "Jones", Age = 21 };
            Person p3 = new Person() { FirstName = "Jame", LastName = "Smith", Age = 28 };
    
            List people = new List(new Person[] { p1, p2, p3 });
    
            IEnumerable foundPeople = people.Where(p => p.GetType().GetProperty("LastName").GetValue(p,null).ToString().StartsWith("J"));
    
            foreach (Person person in foundPeople)
            {
                Console.WriteLine(person.ToString());
            }
            Console.ReadKey();
        }
    }
    

    Just be careful because this could lead to performance issues if you are querying a large amount data.

提交回复
热议问题