Search code examples
linqdynamics-crm-2011dynamics-crmdynamics-crm-4

LINQ Substring CRM 2011


I have a LINQ query that pulls down some information based on certain criteria in the Where clause from CRM 2011. But I want to add it so it only looks at the first 5 characters of the Zip instead of the whole Zip. I tried adding SubString. But if the value is null it will fail. How would you go about matching the first 5 characters of the Zip in the Where clause. This is my query.

var lQuery = (from a in gServiceContext.CreateQuery("account")
    where (a["name"].Equals(lLead.AccountName) &&
        a["address1_postalcode"].Equals(lLead.ZipCode) &&
        a["address1_stateorprovince"].Equals(lLead.State)) ||
        (a["address1_line1"].Equals(lLead.Address1) &&
        a["address1_postalcode"].Equals(lLead.ZipCode) &&
        a["address1_city"].Equals(lLead.City))
    select new
    {
        Name = !a.Contains("name") ? string.Empty : a["name"],
        City = !a.Contains("address1_city") ? string.Empty : a["address1_city"],
        State = !a.Contains("address1_stateorprovince") ? string.Empty : a["address1_stateorprovince"],
        Zip = !a.Contains("address1_postalcode") ? string.Empty : a["address1_postalcode"],
        AccountId = !a.Contains("accountid") ? string.Empty : a["accountid"]
    })

Thanks!


Solution

  • One of the other issues with String.Substring is that it throws if the string isn't long enough, i.e. you try to get the first 5 characters of a 4 character string. You can use a simple helper method like this:

    where First(a["address1_postalcode"], 5) == lLead.ZipCode
    

    (You might need to convert or cast a["address1_postalcode"] to string depending on what type it returns.)

    public static string First(string s, int charcount)
    {
        if (s == null) return String.Empty;
        return s.Substring(0, Math.Min(s.Length, charcount));
    }