How to compare strings in Linq Query

CompareTo does not work for me.

My linq request

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

and em getting an exception

//////AN EXCEPTION///////////

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

My code is 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 in this line

IEnumerator<Customer> resultEnum = result.GetEnumerator();
+5
source share
4 answers

try the following:

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

Quote from your comment "I am comparing a user entered value with a collection of objects that I have to search for clients with identifiers less or you can say more than what the user entered."

try this for more than:

int customerId = int.Parse(txtSerchId.Text);
if (customerId > 0)
{
   var result = from c in customers where c.CustomerID > customerId select c;
}

Strike>

Refresh, as more information has been added in the comments:

Try the following:

customers.ToList().Where(c => c.CustomerID.CompareTo(txtSerchId.Text) >= 0);

, , , THEN . , , , .

0

Plain:

  • For equality:

    var result = from c in customers where c.CustomerID ==Convert.ToInt32(txtSerchId.Text) select c;

  • For more: where c.CustomerID >= Convert.ToInt32(txtSerchId.Text)

  • For less: where c.CustomerID <= Convert.ToInt32(txtSerchId.Text)

0
source
 var List = (from t in ObjCon.TableName
                            where t.GameDate.Value.CompareTo(GameDate) >= 0
                            join t1 in ObjCon.Teams on t.Home equals t1.TeamId
                            where t1.SportId == 3

* It worked for me

0
source

All Articles