How to make LINQ execute a (SQL) LIKE range search

后端 未结 3 1123
北恋
北恋 2020-12-06 23:29

I am in big need of help, i have been trying to do this for some time now.

So I have this Query:

Select name from BlaBlaBla

order by 

case when nam         


        
3条回答
  •  北荒
    北荒 (楼主)
    2020-12-06 23:59

    If I was you I wouldn't try using Expressions to solve this issue since it brings in a lot of complexity.

    I see that you would like to have a generic method, so it can work with different domain entities, yet you are expecting that each entity has a Name property. You can solve this in a more simple way by defining interface that contains Name property. Like this:

        public static void Main()
        {
            var test = new List()
            {
                new YourDomainEntity() { Name = "1test", OtherProperty = "1"},
                new YourDomainEntity() { Name = "2test",  OtherProperty = "2" },
                new YourDomainEntity() { Name = "2test", OtherProperty = "1"   }
            };
    
            var k = Foo(test).ToList();
        }
    
        public interface INameOrderable
        {
            string Name { get; set; }
        }
    
        public interface IOtherPropertyOrderable
        {
            string OtherProperty { get; set; }
        }
    
        public static IEnumerable Foo(IEnumerable list) where T : INameOrderable, IOtherPropertyOrderable
        {
            return list.OrderBy(a => a.Name, new NamesDescComparer()).ThenBy(b => b.OtherProperty);
        }
    
        public class NamesDescComparer : IComparer
        {
            public int Compare(string x, string y) => -String.CompareOrdinal(x, y);
        }
    
        class YourDomainEntity : INameOrderable, IOtherPropertyOrderable
        {
            public string OtherProperty { get; set; }
            public string Name { get; set; }
        }
    

    I believe the method Foo is what you are looking for.

    Note the where T : INameOrderable part. It restricts usage of this method to entities that implement INameOrderable interface

提交回复
热议问题