LastIndexOf in LINQ to Entities

心已入冬 提交于 2019-12-21 12:36:32

问题


I'm using LINQ to Entities to fetch elements from a MSSQL data base and I need them sorted by the last index of a string:

var data = db.GetEntities().
           OrderBy(e=>e.StringProperty.LastIndexOf("Foo")).ToList()

However, LINQ to Entities does not support LastIndexOf. I've tried searching for similar questions but all I've found was this which does not address my issue (ordering). Searching on MSDN did not yield any results.

What would be the simplest way to accomplish this using LINQ to Entities (I don't want to have to do this after the ToList()).


回答1:


You could try

OrderBy(e => e.StringProperty.Length - EntityFunctions.Reverse(e.StringProperty).IndexOf("ooF"))

I think Reverse and IndexOf are supported.




回答2:


Do the sorting using LINQ to Objects

var data = db.GetEntities()
    .AsEnumerable()
    .OrderBy(e => e.StringProperty.LastIndexOf("Foo"))
    .ToList();

Using AsEnumerable will allow you to retain deferred execution, it's the better compromise than calling ToList and then performing the OrderBy.



来源:https://stackoverflow.com/questions/21140076/lastindexof-in-linq-to-entities

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!