gpt4 book ai didi

c# - 如何根据顺序排序

转载 作者:可可西里 更新时间:2023-11-01 09:05:05 24 4
gpt4 key购买 nike

假设我有元素

items : [{id:1,...}, {id:2,...}, {id:3,...}]

并且有排序:[2, 3, 1] 得到一个可枚举的

items : [{id:2,...}, {id:3,...}, {id:1,...}]

我希望它符合

items.Select(o => new {key = ordering[i++], value = o})
.OrderBy(k => k.key)
.Select(o => o.value)

但是有更清洁的解决方案吗?


以下我已经验证了该工作(HimBromBeere、Domysee、qxg)

var expectedOrder = ordering.Select(x => result.First(o => o.Id == x));
var expectedOrder = result.OrderBy(item => Array.FindIndex(ordering,i => i == item.Id));
var expectedOrder = result.OrderBy(item => ordering.ToList().FindIndex(i => i == item.Id));
var expectedOrder =
from o in ordering
join i in result
on o equals i.Id
select i;

Fwi,这是为了验证测试:

    [Test]
[TestCase(1, 2, 3)]
[TestCase(1, 3, 2)]
[TestCase(2, 1, 3)]
[TestCase(2, 3, 1)]
[TestCase(3, 1, 2)]
public void Test_Should_Fail_If_GetMessages_Does_Not_Return_Sorted_By_Sent_Then_By_Id_Result(params int[] ordering)
{
var questions = GetQuestionsData();
Mock.Get(_questionService)
.Setup(o => o.GetQuestions())
.Returns(questions);
var result = _mailboxService.GetMessages();
var expectedOrder = ordering.Select(x => result.First(o => o.Id == x));

// Act
Action sortOrder = () => expectedOrder.Should()
.BeInDescendingOrder(o => o.Sent)
.And.BeInDescendingOrder(o => o.Id);

// Assert
sortOrder.ShouldThrow<AssertionException>();
}

最佳答案

我猜是这样的:

var result = ordering.Select(x => items.First(y => y.id == x.id));

工作示例:

var items = new[] { new { id = 1, name = "1" }, new { id = 2, name = "2" }, new { id = 3, name = "3" }, new { id = 4, name = "4" } };
var result = new[] { 2, 3, 1 }.Select(x => items.First(y => y.id == x));

这也会过滤掉那些 items,其索引不包含在 ordering 中。

关于c# - 如何根据顺序排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34223684/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com