如何在Linq查询中比较字符串

时间:2012-05-04 12:00:02

标签: c# linq argumentexception

CompareTo不适合我。

我的linq查询是

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

和em得到例外

//////例外///////////

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

我的代码是这样的

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");
}

异常就在这一行

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

4 个答案:

答案 0 :(得分:5)

试试这个:

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

答案 1 :(得分:0)

引用您的评论“我将用户输入的值与我拥有的对象集合进行比较,以搜索ID低于或者您可以说比用户输入的ID更高的客户。”

<击> 试试这个“大于”:

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

<击>

更新,因为评论中添加了更多信息:

试试这个:

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

请注意,这是非常低效的,因为它首先从数据库中提取所有记录,然后根据您的字符串比较过滤它们。但说实话,我不知道更好的方法,所以这可能值得一试。

答案 2 :(得分:0)

简单说明:

  1. 平等:

    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. 少见:where c.CustomerID <= Convert.ToInt32(txtSerchId.Text)

答案 3 :(得分:0)

 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

*这适用于我