MBasit
MBasit

Reputation: 101

How to Compare strings in Linq Query

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();

Upvotes: 10

Views: 75333

Answers (4)

Praveen Kumar Rejeti
Praveen Kumar Rejeti

Reputation: 243

 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

*This Worked FOR ME

Upvotes: 0

user2905764
user2905764

Reputation:

Go simple:

  1. For Equality:

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

  2. For Greater : where c.CustomerID >= Convert.ToInt32(txtSerchId.Text)

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

Upvotes: 0

Bazzz
Bazzz

Reputation: 26937

Quoting from your comment "i am comparing user entered value to collection of objects i have, to search Customers having IDs less than or you can say greater than that entered by user."

try this for "greater than":

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

Update as more infomation has been added in comments:

Try this:

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

Notice that this is vastly inefficient as it first pulls ALL records from the database and THEN filters them according to your string comparison. But to be honest I don't know a better way so this might be worth a try.

Upvotes: 0

Ovais Khatri
Ovais Khatri

Reputation: 3211

try this :

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

Upvotes: 11

Related Questions