Find all items in list which exist in another list using linq

I just wanted to go through a few examples of how to retrieve all the items in a list, that also exist in another list. This is one of those useful techniques which you may not need very often and so this post will act as a reminder.

To start with we need arrays.

var lista = new List<string>(){"one","two","three","four","five","six","seven"};
var listb = new List<string>(){"One","fortyfour","six"};

These examples are designed on the principle that we want to retrieve all the values from lista which also exist in listb. This can be done by using an explicit linq join,

result = from a in lista
    join b in listb on a.ToLower() equals b.ToLower()
    select a;

Although it could be written on a single line, this type of query is usually written over multiple lines for clarity. The same result could be achieved as below

result = lista.Where(a => listb.Any(b => a.ToLower() == b.ToLower()));

One method is not necessarily better than the other and I am sure there are a number of other ways the same result could be achieved.
I find using the string.Compare() method saves from having to keep converting to lower case.

var result = lista.Where(a => listb.Any(b => string.Compare(a,b,true) == 0));

If you were to output the contents of the result variable from both the above examples you would see they all produce the same result (based on the original array contents)

one
six

The last example will retrieve all the items from lista where the text of the item is contained in the text of an item in listb.

var result = lista.Where(a => listb.Any(b => b.Contains(a)));

Note that the Contains method is case sensitive so the result would be

four
six

because listb has an item that contains the text ‘four’, which is the text of an item in lista. Also both lists have an item with the same text ‘six’.

JQuery Autocomplete Example With ASP.NET Webforms

This will be a quick run through of how I implemented autocomplete in a Webforms application.

The data for the autocomplete list is represented in a class.

public class Depot
{
    public string DepotCode { get; set; }
    public string DepotName { get; set; }
}

A WebMethod in a service class is called to retrieve the list. I am keeping the amount of the data small for brevity. In this simple example I am checking what the search term starts with and populating a list with similar values. In a real situation the list being returned from this WebMethod would be generated from a search in a database.

[WebMethod]
public List<Depot> GetDepots(string search)
{
    if (search.StartsWith("11"))
    {
        return new List<Depot>{ 
            new Depot{DepotCode= "1111",DepotName= "London"},
            new Depot{DepotCode= "1122",DepotName= "Birmingham"}
        };
    }
    else
    {
        return new List<Depot>{ 
            new Depot{DepotCode= "0111",DepotName= "London"},
            new Depot{DepotCode= "0122",DepotName= "Birmingham"}
        };
    }
}

This javascript is the magic. The request parameter of the source function contains the search text, in this case the text I enter into the input box. I have set minLength to 2, so 2 characters must be entered for the autocomplete list to appear.

In the success function each item of data is transposed into an object consisting of a value and label property. The label property is the text displayed in the autocomplete list.  When an item in the list is selected the Value property is the text that populates the input box.

$("#txtDepotCode").autocomplete({
    source: function (request, response) {
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "creditqueryservice.asmx/GetDepots",
            data: "{'search':'" + request.term + "'}",
            dataType: "json",
            success: function (data) {
                response($.map(data.d, function (item) {
                    return {
                        value: item.DepotCode,
                        label: item.DepotCode +' - '+ item.DepotName
                    };
                }));
            },
            error: function (result) {
                alert("Error");
            }
        });
    },
    minLength: 2
});

There could potentially be any number of issues but I got this issue

object doesn't support property or method 'curCSS'

which turned out to be a mismatch between the version of jQuery and the version of jQueryUI. After changing the version of jQueryUI this issue went away.