[英]Linq query return true or false
我有一个查询,它应该返回TRUE或FALSE。
var query = from c in db.Emp
from d in db.EmpDetails
where c.ID == d.ID && c.FirstName == "A" && c.LastName == "D"
// It should return TRUE when this above statement matches all these conditions
我想将此查询结果附加到一个属性(字符串数据类型)
this.result = Conert.ToBoolean(query);
如何在LINQ中实现这一目标?
编辑:
EmpMapper类
public class EmpMapper
{
EmpEntities db;
// ID column already exists in the DB
private int ID;
// I am creating this property to add it from the UI side, depending on the certain conditions in the query. That is why I created a separate class to map the existing ID from the DB
bool result;
public EmpMapper(int ID, bool result)
{
this.db = new EmpEntites();
this.ID = ID;
var query = from c in db.Emp
from d in db.EmpDetails
where c.ID == d.ID && c.FirstName == "A" && c.LastName == "D"
// It should return TRUE when this above statement matches all these conditions
this.result = Convert.ToBoolean(query);
}
public int ID
{
get{return this.ID;}
set{this.ID = value;}
}
public bool result
{
get{return this.result;}
set{this.result = value;}
}
}
MainViewModel类
List<EmpMapper> empMapCol = new List<EmpMapper>();
private void Page_Loaded(object sender, RoutedEventArgs e)
{
var emp_query = from c in db.Emp
orderby c.ID
select a;
List<Emp> empCol = emp_query.ToList();
foreach(Emp item in empCol)
{
this.empMapCol.Add(new EmpMapper(item.ID, item.result));
}
datagrid1.ItemsSource = empMapCol;
}
}
尝试这个,
var query = (from c in db.Emp
from d in db.EmpDetails
where c.ID == d.ID && c.FirstName == "A" && c.LastName == "D"
select c
).Any();
this.result = query; //no need to convert to boolean its already bool value
如果我对您的理解正确,那么如果查询结果之一与所有条件都匹配,则希望得到true
。 在这种情况下,请尝试以下操作:
var found =
(from c in db.Emp
from d in db.EmpDetails
where c.ID == y.ID && c.FirstName == "A" && c.LastName == "D"
select c).Any();
this.result = found.ToString();
您可以使用.Any()或.Count()。 Any()的性能更好。 (检查此SO问题以了解原因)
。任何()
var query = from c in db.Emp
from d in db.EmpDetails
where c.ID == d.ID && c.FirstName == "A" && c.LastName == "D"
// It should return TRUE when this above statement matches all these conditions
this.result = query.Any().ToString()
。计数()
var query = from c in db.Emp
from d in db.EmpDetails
where c.ID == d.ID && c.FirstName == "A" && c.LastName == "D"
// It should return TRUE when this above statement matches all these conditions
this.result = (query.Count() > 0).ToString()
var query = from c in db.Emp
from d in db.EmpDetails
select new { c.ID == y.ID &&
c.FirstName == "A" &&
c.LastName == "D" };
如果您确实希望拥有“ true”或“ false”字符串响应:
public string result
{
get
{
return db.Emp.SelectMany(c => db.EmpDetails, (c, d) => new {c, d})
.Where(@t => c.ID == y.ID && c.FirstName == "A" && c.LastName == "D")
.Select(@t => c)).Any().ToString();
}
}
但是我建议使属性“结果”成为布尔值并删除ToString()。 有了布尔之后,就可以随时对其执行ToString()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.