C# 如何将Linq中返回的null值更改为IQueryable
我试图用C#中IQueryable上的LINQ查询结果填充listview控件。这应该是世界上最简单的操作,但我对asp.net、c#和visual studio还不熟悉。我所拥有的是:C# 如何将Linq中返回的null值更改为IQueryable,c#,asp.net,linq,C#,Asp.net,Linq,我试图用C#中IQueryable上的LINQ查询结果填充listview控件。这应该是世界上最简单的操作,但我对asp.net、c#和visual studio还不熟悉。我所拥有的是: var query = from i in _db.ItemListView where (!string.IsNullOrEmpty(key)) ? i.Description.Contains(key) : true &&
var query = from i in _db.ItemListView
where (!string.IsNullOrEmpty(key)) ? i.Description.Contains(key) : true &&
DbGeography.FromText(i.Point).Distance(DbGeography.FromText(geog))*0.0006214 <= rng &&
(cat != null) ? i.CategoryID == cat : true &&
(sub != null) ? i.SubCategoryID == sub : true &&
(min != null) ? i.AskingPrice >= min : true &&
(max != null) ? i.AskingPrice <= max : true
orderby i.Distance ascending, i.AskingPrice ascending
select i;
return query;
geog
是一个基于邮政编码经纬度的变量
有人能告诉我怎么做吗?听起来你需要定制
选择:
...
select new {
// other fields here,
...
MyNewDistanceField = DbGeography.FromText(i.Point).Distance(DbGeography.FromText(geog))
}
或者,将输出字段映射到自定义类:
select YourCustomClass {
// other fields here,
...
MyNewDistanceField = DbGeography.FromText(i.Point).Distance(DbGeography.FromText(geog))
}
YourCustomClass
将包含所需的字段定义。您需要计算距离,然后选择包含该距离的新对象。比如:
var query = from i in _db.ItemListView
let dist = DbGeography.FromText(i.Point).Distance(DbGeography.FromText(geog))
where (!string.IsNullOrEmpty(key)) ? i.Description.Contains(key) : true &&
dist*0.0006214 <= rng &&
(cat != null) ? i.CategoryID == cat : true &&
(sub != null) ? i.SubCategoryID == sub : true &&
(min != null) ? i.AskingPrice >= min : true &&
(max != null) ? i.AskingPrice <= max : true
orderby dist ascending, i.AskingPrice ascending
select new WhateverYourClassNameIs(constructor parameters here);
return query;
是因为i.Distance返回null,所以orderby无法正常工作吗?我不太明白你的问题。Linq主要是一种只读模式;如果您试图将数据写入某些内容,则需要执行不同的操作。i.Distance始终为null。我想将其值更改为:DbGeography.FromText(I.Point)、Distance(DbGeography.FromText(geog))并按结果排序。遍历查询对象中的记录,并将I.Distance字段更改为所需的值。然后对结果运行一个新的linq查询,以获得正确的顺序。我不会尝试将结果写回sql server。我正试图在listview控件的结果集中添加一个可用的距离字段!!我尝试了同一个东西的三个变体,但运气不好,但是当我剪切并粘贴了您的代码,并做了一些更改时,它成功了!非常感谢吉姆·迈克尔!
var query = from i in _db.ItemListView
let dist = DbGeography.FromText(i.Point).Distance(DbGeography.FromText(geog))
where (!string.IsNullOrEmpty(key)) ? i.Description.Contains(key) : true &&
dist*0.0006214 <= rng &&
(cat != null) ? i.CategoryID == cat : true &&
(sub != null) ? i.SubCategoryID == sub : true &&
(min != null) ? i.AskingPrice >= min : true &&
(max != null) ? i.AskingPrice <= max : true
orderby dist ascending, i.AskingPrice ascending
select new WhateverYourClassNameIs(constructor parameters here);
return query;
select new Whatever { field1=value, field2=value, etc. };