Search code examples
c#lambda

C# Lambda ignore case


I want to ignore case using this LAMBDA query:

public IEnumerable<StationDto> StationSearch(string search)
        {
            var data = GenerateDtos();

            var list = data.Where(x => x.StationName.Contains(search));




            //var searchDto = new SearchDto {



            return null;
        }



        private static IEnumerable<StationDto> GenerateDtos()
        {
            return new List<StationDto>()
            {
                new StationDto()
                {
                    StationId = 1,
                    StationName = "DARTFORD"
                },
                new StationDto()
                {
                    StationId = 2,
                    StationName = "DARTMOUTH"
                },
                new StationDto()
                {
                    StationId = 3,
                    StationName = "TOWER HILL"
                },
                new StationDto()
                {
                    StationId = 4,
                    StationName = "DERBY"
                },
                new StationDto()
                {
                    StationId = 5,
                    StationName = "lIVERPOOL"
                },
                new StationDto()
                {
                    StationId = 6,
                    StationName = "LIVERPOOL LIME STREET"
                },
                new StationDto()
                {
                    StationId = 7,
                    StationName = "PADDINGTON"
                },
                new StationDto()
                {
                    StationId = 8,
                    StationName = "EUSTON"
                },
                new StationDto()
                {
                    StationId = 9,
                    StationName = "VICTORIA"
                },
            };
        }
    }

If I search for "DAR" it will bring back two but "dar" brings back 0 items. How would I modify this query?


Solution

  • Assuming you're talking about x.StationName.Contains(search) you could do

    var list = data
      .Where(x => x.StationName.IndexOf(search, StringComparison.OrdinalIgnoreCase) >= 0)
    

    You could also add a String extension method

    public static class StringExtensions
    {
        public static bool Contains(this string thisObj, string value, StringComparer compareType) 
        {
            return thisObj.IndexOf(value, StringComparison.OrdinalIgnoreCase) >= 0;
        }
    }
    

    and use it like this

     var list = data
       .Where(x => x.StationName.Contains(search, StringComparison.OrdinalIgnoreCase));