Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何对由ID列表创建的LinQ结果集进行排序,并使用列表的现有顺序对其进行排序_Linq_Sorting - Fatal编程技术网

如何对由ID列表创建的LinQ结果集进行排序,并使用列表的现有顺序对其进行排序

如何对由ID列表创建的LinQ结果集进行排序,并使用列表的现有顺序对其进行排序,linq,sorting,Linq,Sorting,我的代码是这样的: List<int> IDs = new List<int> {9,7,38, 23} IQueryable<Post> pp = myDataEntity.Posts.Where(p=>IDs.Contains(p.ID)); List id=新列表{9,7,38,23} IQueryable pp=myDataEntity.Posts.Where(p=>IDs.Contains(p.ID)); 我如何解释我想按照ID在ID中的顺

我的代码是这样的:

List<int> IDs = new List<int> {9,7,38, 23}
IQueryable<Post> pp = myDataEntity.Posts.Where(p=>IDs.Contains(p.ID));
List id=新列表{9,7,38,23}
IQueryable pp=myDataEntity.Posts.Where(p=>IDs.Contains(p.ID));
我如何解释我想按照ID在ID中的顺序对pp进行排序?谢谢。

使用

IQueryable pp=myDataEntity.Posts.Where(p=>IDs.Contains(p.ID))
.OrderByDescending(p=>p.ID)

假设您希望保持ID在IDs中的顺序,而不是实际的顺序验证,您可以这样做:

var pp = IDs.Select(x=> myDataEntity.Posts.Where(p=>p.ID == x))
            .SelectMany(x=>x);
使用ID作为外部集合,您可以保持其中元素的顺序。

您可以通过以下方式进行排序:

IQueryable orderedPosts myDataEntity.Posts
.Select(p=>new{Post=p,Index=IDs.IndexOf(p.ID)})
.其中(x=>x.索引>=0)
.OrderBy(x=>x.Index)
.选择(x=>x.Post);

我认为他希望保持IDs中的顺序(首先是9的匹配,然后是7的匹配,然后是38的匹配,然后是23的匹配),而不是我需要的顺序版本。在确认之前我需要多一点时间(现在不是在电脑前)。关于“.Where(x=>x.Index>=0)”,您能再清楚一点吗?在这种情况下,x.Index可以是@user2742377:如果在集合中找不到元素,则返回
-1
。因此,您可以将其用于这两种情况,确定是否包含它以及在哪个索引处(对于订单)。我使用了匿名类型来存储这个值,否则我将需要它两次(
Where
+
OrderBy
)。啊,当ID不在IDs中时会发生这种情况。谢谢
var pp = IDs.Select(x=> myDataEntity.Posts.Where(p=>p.ID == x))
            .SelectMany(x=>x);
IQueryable<Post> orderedPosts myDataEntity.Posts
    .Select(p  => new { Post=p, Index=IDs.IndexOf(p.ID) })
    .Where(x   => x.Index >= 0)
    .OrderBy(x => x.Index)
    .Select(x  => x.Post);