简体   繁体   中英

How can I return ToList() using the where and select Linq?

I have this code below and I want to return all the list of postcode that matches the filter. The highlighted code is throwing error codes (CS0029 and CS1662). Any help from someone?

public static IQueryable<Address> GetAdressSearchFilter(this IQueryable<Address> query, AddressSearchBaseQuery request)
        {
            if (!string.IsNullOrWhiteSpace(request.PostCode))
            {
                var trimPostCode = request.PostCode.TrimEnd();
                if (trimPostCode.Contains(" "))
                {
                    query = query.Where(l => l.Postcode.Contains(trimPostCode) || l.Postcode.Contains(trimPostCode.Replace(" ", String.Empty)));
                }
                else
                {
                    var postCodeList = new List<string>();
                    for (int i = 0; i < trimPostCode.Length; i++)
                    {
                        postCodeList.Add(String.Join(" ", Regex.Split(trimPostCode, $@"(?<=[{trimPostCode[i]}])")).Trim());
                    }
                     //The error is on the line below
                    query = query.Where(l => postCodeList.Any(p => l.Postcode.Contains(p))
                    );
                }
            }

            return query;
        }

Start with CS1662 - "Cannot convert anonymous method block to delegate type 'delegate type' because some of the return types in the block are not implicitly convertible to the delegate return type"

The Where method expects a delegate which takes an item from your input data, and returns a bool indicating whether or not that item should be included.

The delegate you've passed in is:

l => postCodeList.Select(p => l.Postcode.Contains(p)).ToList()

That takes an item from your list, and returns a list of bool values .

That clearly doesn't match the requirements of the Where method.

Change your code to:

query = query.Where(l => postCodeList.Any(p => l.Postcode.Contains(p)));

Once you've fixed that error, the CS0029 error should also disappear.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM