如何按照 id 的自定义顺序从表中获取记录?

2024-04-26

我有一些Ids存储在下面的变量中:

List<int> Ids;

现在我想根据上面的 ID 获取记录,但顺序与上面相同Ids.

例如:数据库中的记录是这样的:

员工:

Id
1
2
3
4
5

现在,如果 Ids 数组包含这样的 Id:4,2,5,3,1然后我尝试仅按此顺序获取记录:

Query:

  var data = context.Employee.Where(t => Ids.Contains(t.Id)).ToList();

但上面的查询给了我像表中一样的输出:

Id
1
2
3
4
5

预期输出:

Id
4
2
5
3
1

Update:我已经尝试过下面的解决方案,但由于这是实体框架,所以没有成功:

var data = context.Employee.Where(t => Ids.Contains(t.Id))
                    .OrderBy(d => Ids.IndexOf(d.Id)).ToList();

为了使上述解决方案正常工作,我必须添加到列表中:

var data = context.Employee.Where(t => Ids.Contains(t.Id)).ToList()
                    .OrderBy(d => Ids.IndexOf(d.Id)).ToList();

但我不想将数据加载到内存中,然后过滤掉我的记录。


由于未指定时返回数据的顺序ORDER BY is 还没决定 https://stackoverflow.com/questions/10064532/the-order-of-a-sql-select-statement-without-order-by-clause,你必须添加一个ORDER BY指示您希望如何排序。不幸的是,您必须根据内存中的对象/值进行排序,并且不能使用它在 SQL 查询中进行排序。

因此,您能做的最好的事情就是从数据库检索数据后在内存中进行排序。

var data = context.Employee
    // Add a criteria that we only want the known ids
    .Where(t => Ids.Contains(t.Id))
    // Anything after this is done in-memory instead of by the database
    .AsEnumerable()
    // Sort the results, in-memory
    .OrderBy(d => Ids.IndexOf(d.Id))
    // Materialize into a list
    .ToList();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何按照 id 的自定义顺序从表中获取记录? 的相关文章

随机推荐