How to Compare strings in Linq Query

MBasit picture MBasit · May 4, 2012 · Viewed 59.4k times · Source

CompareTo is not working here for me.

My linq query is

var result = from c in customers 
             where c.CustomerID.CompareTo(txtSerchId.Text) >= 0 
             select` c;

and em getting an exception

//////EXCEPTION///////////

System.ArgumentException was caught
Message=Value does not fall within the expected range.

My code is something like this

var result = 
    from c in customers 
    where c.CustomerID.CompareTo(txtSerchId.Text) >= 0 
    select c;

if (result != null)
{
    IEnumerator<Customer> resultEnum = result.GetEnumerator();
    while (resultEnum.MoveNext())
    {
        Customer c = (Customer)resultEnum.Current;
        addToDataSet(Guid.NewGuid().ToString(), c);
    }
    ShowResult();
}
else
{
    MessageBox.Show("No Customer found within criteria");
}

exception is at this line

IEnumerator<Customer> resultEnum = result.GetEnumerator();

Answer

Ovais Khatri picture Ovais Khatri · May 4, 2012

try this :

var query = from c in customers where c.CustomerID.Equals(txtSerchId.Text) select c;