linq计数与检查字符串StartsWith

时间:2013-09-14 18:09:33

标签: linq windows-phone-7 count startswith

现在我的代码当名称条目重复时它会计算重复的名称&在名称旁边添加计数编号,如

如果数据库已经有'Andy'名称 接下来Andy将被添加为'Andy 1'

但问题是如果我将另一个'Andy'添加到数据库中,当它找到'Andy'它变成'Andy 1'时会检查重复但是它再次找到'Andy 1',所以最后它被保存为'Andy 1 1'所以我无法弄清楚如何通过'Andy 1'然后'Andy 2'然后'Andy 3'来保存它

private void button0_Click(object sender, EventArgs e)
    {
        using (DBDataContext DB = new DBDataContext(strConnectionString))
        {
            Table newTable = new Table
            {
                Name = txtName.Text.ToString(),
                Add = txtAdd.Text.ToString(),
            };

            var a = from b in DB.GetTable<Table>() select b;

            foreach (var x in a)
            {
                if (x.Name == txtName.Text.ToString())
                {
                    txtCOUNT.Text = a.Count(b => b.Name == txtName.Text).ToString();

                    MessageBox.Show("This Name is already Exists");

                    Check = txtName.Text + " " + txtCOUNT.Text;

                    txtName.Text = Check;

                    txtAdd.Text = " ";

                    id = x.Id;
                }
            }

            if (txtName.Text != "" && txtAdd.Text != "")
            {
                DB.NTable.InsertOnSubmit(newTable);

                DB.SubmitChanges();

                MessageBox.Show("Name Added Successfully.", "Done!", MessageBoxButton.OK);

                NavigationService.GoBack();
            }
            else
            {
                MessageBox.Show("Some essential details must be entered. Name, Add.", "Details Missing!", MessageBoxButton.OK);
            }
        }
    }

我正在尝试在Counting中使用字符串StartsWith

string Check = txtName.Text;

txtCOUNT.Text = a.Count (b => b.Name == Check.StartsWith(b.Name)).ToString();

但没有给我错误请帮助

2 个答案:

答案 0 :(得分:1)

首先要注意的是:当你这样做时:

var a = from b in DB.GetTable<Table>() select b;

foreach (var x in a)
{

它会加载每一行(而不是影响数据库查询),如果有很多行,这可能会很昂贵。

这是一个Linq查询,我认为它会做你想要的(如果txtName.Text中的名称只包含文本,它将起作用):

using (DBDataContext DB = new DBDataContext(strConnectionString))
{
            string name = txtName.Text.ToString(),
            int nbDuplicate = (from b in DB.GetTable<Table>()
                    where b.Name==name ||  b.Name.StartsWith(name+" ") 
                       && (b.Name.Length>=name.Length+2 && 
                    b.Name[name.Length+1]>='0'
                    && b.Name[name.Length+1]<='9'
                      )
                    select b).Count();
            name +=  " " + nbDuplicate;
              .....
}

答案 1 :(得分:0)

这是您的查询

var countNumber = (from c in svcContext.ContactSet
                     where c.FirstName.StartsWith("Andy")
                     select new
                     {
                      c.FirstName,
                      c.LastName
                     }).Count();

由于这会返回一个可观察的集合集,那么我们显然会调用count来获取元素的数量。 Linq to Sql中的计数实现就像没有Linq查询计数一样。

检查Msdn链接

Count In Linq