我的目标是按群组分割IEnumerable的船只。 船舶组是相距0.5英里的船舶。
UPD:说我们有一条河,像密西西比河。船只漂浮在船上。 我的目标是根据他们的位置对他们进行分组。不是坐标而是里程(例如19.3英里),这样如果我们有一艘船在19.3英里而另一艘在19.5英里,我们将它们聚集成一组。但如果我们在193英里处还有另一艘船,我们就无法将它添加到我们刚刚分组的两艘船的组中。 在我们拥有的一系列船舶中没有船只的船只:(所有河流和地方) IEnumerable的。我想知道如何在查询中考虑英里比较?
var orderedShips = from ship in ungroupedShips
orderby string.Intern(ship.River), ship.MileMarker ascending
group ship by string.Intern(ship.River) into shipRiverGroup
select new BargeGroup { Ships = shipRiverGroup };
答案 0 :(得分:1)
我不明白你的linq,但根据你的问题:
您可以使用truncate按数字间隔进行分组,例如:
context.YourTable
.GroupBy(g => (int)g.YourFieldDouble)
.OrderBy(o => o.Key);
这将按整数值分组
如果你想在0.5到0.5组中分组,只需使用乘法和除法:
context.YourTable
.GroupBy(g => (int)(g.YourFieldDouble * 2) / 2.0)
.OrderBy(o => o.Key);
你也可以使用圆形方法:
context.YourTable
.GroupBy(g => Math.Round((double)g.YourFieldDouble * 2,
MidpointRounding.AwayFromZero) / 2.0)
.OrderBy(o => o.Key)
答案 1 :(得分:1)
由于缺乏信息,我会认为你有一个Ship
实体类:
class Ship
{
public int Id { get; set; }
public double MileMarker { get; set; }
public string River { get; set; }
}
所以要在同一条河流中找到彼此相邻的两艘船:
from s1 in context.Ships
from s2 in context.Ships
where Math.Abs(s1.MileMarker - s2.MileMarker) <= 0.5
&& s1.River == s2.River /* guarantee both ships are in same river. */
&& s1.Id != s2.Id /* avoid pair of one ship with itself. */
&& s1.MileMarker < s2.MileMarker /* avoid permutation duplicity */
select new { S1Mile = s1.MileMarker, S2Mile = s2.MileMarker, River = s1.River }
使用如下方案:
Ships = new List<Ship>
{
new Ship { Id = 1, MileMarker = 0.2, River = "San" },
new Ship { Id = 2, MileMarker = 0.4, River = "San" },
new Ship { Id = 3, MileMarker = 0.8, River = "San" },
new Ship { Id = 4, MileMarker = 0.1, River = "Joe" },
new Ship { Id = 5, MileMarker = 0.4, River = "Joe" },
new Ship { Id = 6, MileMarker = 0.3, River = "Joe" },
};
你会得到:
S1Mile S2Mile River
0.2 0.4 San
0.4 0.8 San
0.1 0.4 Joe
0.1 0.3 Joe
0.3 0.4 Joe