如何让Linq只返回相同的重复行一次?

时间:2014-04-11 06:44:22

标签: c# linq

我对此仍然很陌生,所以对我很轻松。当查询返回多个相同的记录时,我试图让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,如何让查询返回每个客户端的单个记录,而不是多个相同的记录?

2 个答案:

答案 0 :(得分:0)

我认为运营商优先级正在影响查询。

尝试在三元运算符周围添加括号。

(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从未被评估过。

答案 1 :(得分:0)

尔加!!我所要做的就是添加一个额外的条件!

var query = from i in _db.BizListView
            let dist = DbGeography.FromText(i.Point).Distance(DbGeography.FromText(geog)) * 0.0006214
            where
                dist <= rng &&
                i.Name.Contains(key) &&
                pri != -1 ? (i.BizCategoryID == pri && i.Primary == true) : true &&
                biz != -1 ? (i.BizCategoryID == biz) : true &&
                (biz == -1 && pri == -1) ? (i.Primary == true): true               
            orderby i.Distance ascending
            select i;
好吧,好吧。生活和学习。