Linq OrderBy取决于条件
本文关键字:条件 取决于 OrderBy Linq | 更新日期: 2023-09-27 18:27:14
我想根据的结果订购一个列表
if(group.Substring(group.Length-1,1)%2==0)
降序else
订单递增
List<CellTemp> orderedCells =
(from shelf in foundCells
where Convert.ToInt32(shelf.Group.Substring(shelf.Group.Length - 1), 1) % 2 == 0
orderby shelf.Grup, shelf.Row descending
select new CellTemp()
{
cod= shelf.cod,
PN = shelf.PN,
Description = shelf.Description,
Group= shelf.Group,
Row= shelf.Row,
Shelf= shelf.Shelf
}).ToList();
我怎样才能保留第一个架子。将OrderBy和OrderBy shelf分组。行升序或降序取决于shelf。群是奇数还是偶数?
shelf.group的格式为"group_A0"。
--------------------编辑-----------------------
很抱歉造成混乱。我想做这样的事。
var orderCells = (from shelf in celuleGasite
where Convert.ToInt32(shelf.Gruup.Substring(shelf.Group.Length - 1, 1)) % 2 == 0
orderby shelf.Group, shelf.Row descending
where Convert.ToInt32(shelf.Group.Substring(shelf.Group.Length - 1, 1)) % 2 == 1
orderby shelf.Group, shelf.Row ascending
select shelf).ToList();
但该列表有0个元素
也许这就是您想要的:
var orderCells = (from shelf in celuleGasite
where Convert.ToInt32(shelf.Group.Substring(shelf.Group.Length - 1, 1)) % 2 == 0
orderby shelf.Group, shelf.Row descending)
.Concat(from shelf in celuleGasite
where Convert.ToInt32(shelf.Group.Substring(shelf.Group.Length - 1, 1)) % 2 == 1
orderby shelf.Group, shelf.Row)
.ToList();
或使用GroupBy
:
var orderCells = celuleGasite.GroupBy(shelf=>Convert.ToInt32(shelf.Group[shelf.Group.Length-1]) % 2)
.Select(g=>g.Key == 0 ? g.OrderBy(shelf=>shelf.Group)
.ThenByDescending(shelf=>shelf.Row) :
g.OrderBy(shelf=>shelf.Group)
.ThenBy(shelf=>shelf.Row))
.SelectMany(x=>x)
.ToList();
在King King的帮助下,我设法找到了解决方案。他的代码可能是从头开始写的:)所以如果你像我一样被卡住了,这里是完整的代码。
var orderCells1 = (from shelf in foundCells
where Convert.ToInt32(shelf.Group.Substring(shelf.Group.Length - 1, 1)) % 2 == 0
orderby shelf.Row descending
select shelf).Concat(from shelf in foundCells
where Convert.ToInt32(shelf.Group.Substring(shelf.Group.Length - 1, 1)) % 2 == 1
orderby shelf.Row
select shelf).OrderBy(grup => grup.Group).ToList();
或使用GroupBy
var orderCells2 = foundCells.GroupBy(shelf=>Convert.ToInt32(shelf.Group[shelf.Group.Length - 1]) % 2)
.Select(g => g.Key == 0 ?
g.OrderByDescending(shelf => shelf.Row) : g.OrderBy(shelf => shelf.Row))
.SelectMany(x => x).OrderBy(group=>group.Group).ToList();