让我说我有物品
items : [{id:1,...},{id:2,{id:3,...}]
并订购:[2,3,1]得到一个可枚举
items : [{id:2,{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,2)] [TestCase(2,1,3)] [TestCase(2,1)] [TestCase(3,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,1 }.Select(x => items.First(y => y.id == x));
这也会排除这些项目,其索引不包含在排序中.