我有两个班级:
public class Customer
{
public string FirstName { get; set; }
public string LastName { get; set; }
public List<Product> Product { get; set; }
}
public class Product
{
public string ProductNumber { get; set; }
public string ProductColor { get; set; }
}
还有一个例子:
Customer[] c = new Customer[]
{
new Customer()
{
FirstName = "FirstName1",
LastName = "LastName1",
Product = new List<Product>
{
new Product()
{
ProductColor = "ProductColor1",
ProductNumber = "11"
}
}
},
new Customer()
{
FirstName = "FirstName2",
LastName = "LastName2",
Product = new List<Product>
{
new Product()
{
ProductColor = "ProductColor2",
ProductNumber = "12"
}
}
}
};
我使用System.Dynamic.Linq
库来过滤我的数组:
var filter = c.Where("FirstName == \"FirstName1\"").Select(x => x).ToList();
我创建了一个类condition
和一个实例:
public class condition
{
public string propertyName { get; set; }
public string propertyValue { get; set; }
}
List<condition> f = new List<condition>
{
new condition()
{
propertyName = "FirstName",
propertyValue = "FirstName1"
},
new condition()
{
propertyName = "Product.ProductColor",
propertyValue = "11"
}
};
我想从此Where
List<Condition>
怎么做?
答案 0 :(得分:1)
从我可以收集的内容中,只是在您的列表中执行此操作的简单案例?除非我错过了什么?
var query = f.Where(x => x.propertyName == "FirstName" && x.propertyValue == "FirstName1");
答案 1 :(得分:0)
为了解决你的问题,我已经修改了你的条件类,如下所示:
客户的条件可能包含产品条件列表:
public class Condition
{
public string propertyName { get; set; }
public string propertyValue { get; set; }
public ICollection<Condition> Conditions { get; set; }
}
创建它:
List<Condition> f = new List<Condition>
{
new Condition()
{
propertyName = "FirstName",
propertyValue = "FirstName1",
Conditions = new List<Condition>
{
new Condition
{
propertyName = "ProductColor",
propertyValue = "11"
}
}
},
};
现在您可以使用以下查询过滤客户和具有给定条件的产品:
var filteredCustomers =
from condition in f
from custmer in c
from product in custmer.Product
let propertyName = condition.propertyName
let propertyValue = condition.propertyValue
where (nameof(custmer.FirstName) == propertyName && custmer.FirstName == propertyValue)
&&
(condition.Conditions.Any(p => p.propertyName == nameof(product.ProductColor))
&& condition.Conditions.Any(p => p.propertyValue == product.ProductNumber))
select custmer;
foreach (var filterCustmer in filteredCustomers.Distinct())
{
Console.WriteLine(filterCustmer.FirstName);
}