我对此还是很陌生,所以请放轻松。当查询返回多个相同的记录时,我试图让 linq 返回单个记录。这是我拥有的:
var query = (from i in _db.BizListView
let dist = DbGeography.FromText(i.Point).Distance(DbGeography.FromText(geog)) * .0006214
where
dist <= rng &&
i.Name.Contains(key) &&
pri != -1 ? (i.BizCategoryID == pri && i.Primary == true) : true &&
biz != -1 ? (i.BizCategoryID == biz) : true
group i by new
{
ClientID = i.ClientID,
Name = i.Name,
Address = i.Address,
Address1 = i.City + ", " + i.StateID + " " + i.PostCode,
BizPhone = i.BizPhone,
EmailAddress = i.EmailAddress,
ClientImagePath = i.ClientImagePath,
Distance = DbGeography.FromText(i.Point).Distance(DbGeography.FromText(geog)) * 0.0006214
}
into myTable
orderby myTable.Key.Distance ascending
select new
{
ClientID = myTable.Key.ClientID,
Name = myTable.Key.Name,
Address = myTable.Key.Address,
Address1 = myTable.Key.Address1,
BizPhone = myTable.Key.BizPhone,
EmailAddress = myTable.Key.EmailAddress,
ClientImagePath = myTable.Key.ClientImagePath,
Distance = myTable.Key.Distance
}).Distinct();
return query;
只要指定了 BizCategory,查询就会为每个客户生成一条记录,但如果没有指定 BizCategory,则查询会为每个客户返回多个相同的记录(每个客户的 BizCategories 的一条记录)。在未指定 BizCategory 时,如何让查询返回每个客户端的单个记录,而不是多个相同的记录?
最佳答案
我相信运算符优先级会影响查询。
尝试在三元运算符周围添加括号。
(pri != -1 ? (i.BizCategoryID == pri && i.Primary == true) : true) &&
(biz != -1 ? (i.BizCategoryID == biz) : true)
表达这种情况的更简单的方法可能是:
(pri == -1 || i.BizCategoryID == pri) &&
(biz == -1 || i.BizCategoryID == biz)
它被解释的方式:
pri != -1
? (i.BizCategoryID == pri && i.Primary == true)
: (true && (biz != -1 ? (i.BizCategoryID == biz) : true))
|< ----- IGNORED ----------------------------->|
您可以看到 true && biz != -1...
在这里优先。由于 true
首先被评估,因此 biz
从未被评估。
关于c# - 如何让 Linq 只返回一次相同的重复行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23005333/