我正在尝试找到一种干净的方法来允许输入可以查询对象结构的字符串。我认为动态 linq 查询是我想要的,但我不知道如何实现它。
用户将输入一个字符串,如
relationship.IsHappy = true or relationship.Type = "Uncle" or relationship.Type = "Uncle" && relationship.IsHappy = true
main() 中的最后两行是我试图找到的解决方案:
string zQuery = args[0];
me.Realtionships.Where(zQuery);
完整代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Linq.Dynamic;
namespace LinqTest1
{
class Program
{
static void Main(string[] args)
{
person me = new person();
me.FirstName = "Andy";
me.Realtionships = new List<relationship>();
person aunt = new person();
aunt.FirstName = "Lucy";
relationship rAunt = new relationship();
rAunt.IsHappy = true;
rAunt.Type = "Aunt";
rAunt.Person = aunt;
me.Realtionships.Add(rAunt);
person uncle = new person();
uncle.FirstName = "Bob";
relationship rUncle = new relationship();
rUncle.IsHappy = false;
rUncle.Type = "Aunt";
rUncle.Person = uncle;
me.Realtionships.Add(rUncle);
string zQuery = args[0];
me.Realtionships.Where(zQuery);
}
}
public class person
{
private string _firstName;
public string FirstName
{
get { return _firstName; }
set { _firstName = value; }
}
private string _lastName;
public string LastName
{
get { return _lastName; }
set { _lastName = value; }
}
private List<relationship> _realtionships;
public List<relationship> Realtionships
{
get { return _realtionships; }
set { _realtionships = value; }
}
}
public class relationship
{
private string _type;
public string Type
{
get { return _type; }
set { _type = value; }
}
private bool _isHappy;
public bool IsHappy
{
get { return _isHappy; }
set { _isHappy = value; }
}
private person _person;
public person Person
{
get { return _person; }
set { _person = value; }
}
}
}