Question

I'm trying to create a list of strings (on a controller method for use as JSON that is consumed by a JQuery Autocomplete on the client). Is there a way to reduce these six or seven lines to two lines? In other words I want the first line to create the IEnumerable of strings.

Also is there a way of not using the custom comparer - all it does is compare strings (on the CompanyMeasureName field).

public JsonResult GetMyMeasureNameList(string term)
{
    //I've defined a custom comparer called NameComparer on the MyMeasure Object
    IEnumerable<MyMeasure> interList = 
        MyMeasure.Distinct(new MyMeasure.NameComparer())
                 .Where(cmo => cmo.CompanyMeasureName
                                  .ToLower()
                                  .Contains(term.ToLower()));

    List<string> retList = new List<string>();
    foreach (var cmo in interList.ToList())
    {
            CompanyMeasure c = (CompanyMeasure)cmo;
            retList.Add(c.CompanyMeasureName);
    }

    return Json(retList, JsonRequestBehavior.AllowGet);
}        

Thanks in advance

Was it helpful?

Solution

The following solves part of the problem (as usual I came up with the answer 5 seconds after posting the question). However I'd still like to be able to not use a custom comparer as it seems pretty pointless.

IEnumerable<MyMeasure> interList = 
    MyMeasure.Distinct(new MyMeasure.NameComparer())
             .Where(cmo => cmo.CompanyMeasureName
                              .ToLower()
                              .Contains(term.ToLower())).Select(m => m.CompanyMeasure);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top