注册 登录
编程论坛 C# 论坛

请教这是泛型吗?怎样操作查询和删除啊?谢谢

brightzhang 发布于 2015-01-04 22:10, 581 次点击
List<Customer> customers = new List<Customer> {
              new Customer { ID="A", City="New York", Country="USA", Region="North America", Sales=9999},
              new Customer { ID="B", City="Mumbai", Country="India", Region="Asia", Sales=8888},
              new Customer { ID="T", City="Lima", Country="Peru", Region="South America", Sales=2002 }
           };
             //想对City="Mumbai",进行操作
            textBox1.Text = customers.IndexOf(这里写什么?).ToString());
            customers.Remove(这里写什么?);
本人是刚学习c#,请教这是泛型变量吗?如果查询其位置、删去其中符合条件的一组数据?
3 回复
#2
over12302015-01-05 09:42
你的textBox1想显示什么内容?应该不能把整个类都显示在里面吧?
你用下面方法试下,看是不是你要的效果:
          var a=customers.Where (b => b.City == "Mumbai");
            if (a.Count() >0)
            {
                textBox1.Text = a.ElementAt(0).City;
                customers.Remove(a.ElementAt(0));
            }
            else
            {
                textBox1.Text = "不存在 Mumbai";
            }
#3
xydddaxia2015-01-05 09:47
程序代码:

List<Customer> customers = new List<Customer> {
    new Customer { ID="1", City="New York", Country="USA", Region="North America", Sales=9999},
    new Customer { ID="2", City="Mumbai", Country="India", Region="Asia", Sales=8888},
    new Customer { ID="3", City="Lima", Country="Peru", Region="South America", Sales=2002 }
};


Customer item = customers[2];
int index = customers.IndexOf(item);//查找元素匹配的索引

bool bl = customers.Remove(item);//移除匹配的元素
Customer firstItem = customers.Find(m => m.City == "New York");//查找City="New York"的第一个元素
List<Customer> allItem = customers.FindAll(m => m.City == "New York");//查找City="New York"的第所有元素
//等同于
//List<Customer> allItem = customers.Where(m => m.City == "New York").ToList();
//List<Customer> allItem = customers.Where(m => m.City == "New York").OrderBy(m=>m.ID).ToList();

Func<int, List<Customer>> fun = new Func<int, List<Customer>>((p) =>
{
    var result = new List<Customer>();
    //foreach (...)
   
//{
   
//    ...
   
//}
    return result;
});
List<Customer> funItems1 = fun(1);
List<Customer> funItems2 = customers.Skip(2).Take(3).ToList();//相当于SubString(2,3)
#4
brightzhang2015-01-07 19:46
谢谢两位,我从你们的回答中找到了答案。
初次到论坛问问题,有什么做的不到的请见谅!
1