How can I find a specific element in a List<T>?

本文关键字:lt gt List in can find specific element How | 更新日期: 2023-09-27 18:29:04

我的应用程序使用这样的列表:

List<MyClass> list = new List<MyClass>();

使用Add方法,将MyClass的另一个实例添加到列表中。

MyClass提供了以下方法:

public void SetId(String Id);
public String GetId();

如何使用GetId方法找到MyClass的特定实例?我知道有Find方法,但我不知道这在这里是否有效?!

How can I find a specific element in a List<T>?

使用lambda表达式

MyClass result = list.Find(x => x.GetId() == "xy");

注意:C#有一个内置的属性语法。与其将getter和setter作为普通方法编写(您可能习惯于从Java编写),不如编写

private string _id;
public string Id
{
    get
    {
        return _id;
    }
    set
    {
        _id = value;
    }
}

value是仅在set访问器中已知的上下文关键字。它表示指定给特性的值。

由于经常使用这种模式,C#提供了自动实现的属性。它们是上面代码的简短版本;但是,后备变量是隐藏的,不可访问(但是,它可以从VB中的类中访问)。

public string Id { get; set; }

您可以像访问字段一样简单地使用属性:

var obj = new MyClass();
obj.Id = "xy";       // Calls the setter with "xy" assigned to the value parameter.
string id = obj.Id;  // Calls the getter.

使用属性,您可以搜索列表中的项目,如

MyClass result = list.Find(x => x.Id == "xy"); 

如果您需要只读属性,也可以使用自动实现的属性:

public string Id { get; private set; }

这使您可以在类内设置Id,但不能从外部设置。如果你也需要在派生类中设置它,你也可以保护设置

public string Id { get; protected set; }

最后,您可以将属性声明为virtual,并在派生类中重写它们,从而允许您为getter和setter提供不同的实现;就像普通的虚拟方法一样。


从C#6.0(Visual Studio 2015,Roslyn)开始,您可以使用内联初始值设定项编写仅getter的自动属性

public string Id { get; } = "A07"; // Evaluated once when object is initialized.

您也可以在构造函数中初始化仅getter属性。仅Getter的自动属性是true只读属性,与使用私有setter的自动实现属性不同。

这也适用于读写自动属性:

public string Id { get; set; } = "A07";

从C#6.0开始,您还可以将属性编写为表达式体成员

public DateTime Yesterday => DateTime.Date.AddDays(-1); // Evaluated at each call.
// Instead of
public DateTime Yesterday { get { return DateTime.Date.AddDays(-1); } }

请参阅:.NET编译器平台("Roslyn")
C#6 中的新语言特性

从C#7.0开始,getter和setter都可以用表达式体编写:

public string Name
{
    get => _name;                                // getter
    set => _name = value;                        // setter
}

请注意,在这种情况下,setter必须是一个表达式。它不能是一个声明。上面的例子是有效的,因为在C#中,赋值可以用作表达式或语句。赋值表达式的值是赋值,其中赋值本身是副作用。这允许您一次为多个变量赋值:x = y = z = 0等效于x = (y = (z = 0)),与语句z = 0; y = 0; x = 0;具有相同的效果。

由于C#9.0,您可以使用只读(或更好地初始化一次)属性,这些属性可以在对象初始化器中初始化。目前,仅使用getter属性是不可能做到这一点的。

public string Name { get; init; }
var c = new C { Name = "c-sharp" };

从C#11开始,您可以使用required属性来强制客户端代码对其进行初始化

field关键字计划用于C#的未来版本(它没有进入C#11,可能也不会进入C#12),并允许访问自动创建的backing字段。

// Removes time part in setter
public DateTime HiredDate { get; init => field = value.Date(); }
public Data LazyData => field ??= new Data();
var list = new List<MyClass>();
var item = list.Find( x => x.GetId() == "TARGET_ID" );

或者如果只有一个,并且你想强制执行像SingleOrDefault这样的东西可能就是你想要的

var item = list.SingleOrDefault( x => x.GetId() == "TARGET" );
if ( item == null )
    throw new Exception();

尝试:

 list.Find(item => item.id==myid);

或者,如果你不喜欢使用LINQ,你可以用老式的方法:

List<MyClass> list = new List<MyClass>();
foreach (MyClass element in list)
{
    if (element.GetId() == "heres_where_you_put_what_you_are_looking_for")
    {
        break; // If you only want to find the first instance a break here would be best for your application
    }
}

您还可以使用LINQ扩展:

string id = "hello";
MyClass result = list.Where(m => m.GetId() == id).First();

使用匿名方法语法编写的谓词可以最简洁地解决问题:

MyClass found = list.Find(item => item.GetID() == ID);
public List<DealsCategory> DealCategory { get; set; }
int categoryid = Convert.ToInt16(dealsModel.DealCategory.Select(x => x.Id));

您可以创建一个搜索变量来保存您的搜索条件。下面是一个使用数据库的示例。

 var query = from o in this.mJDBDataset.Products 
             where o.ProductStatus == textBox1.Text || o.Karrot == textBox1.Text 
             || o.ProductDetails == textBox1.Text || o.DepositDate == textBox1.Text 
             || o.SellDate == textBox1.Text
             select o;
 dataGridView1.DataSource = query.ToList();
 //Search and Calculate
 search = textBox1.Text;
 cnn.Open();
 string query1 = string.Format("select * from Products where ProductStatus='"
               + search +"'");
 SqlDataAdapter da = new SqlDataAdapter(query1, cnn);
 DataSet ds = new DataSet();
 da.Fill(ds, "Products");
 SqlDataReader reader;
 reader = new SqlCommand(query1, cnn).ExecuteReader();
 List<double> DuePayment = new List<double>();
 if (reader.HasRows)
 {
  while (reader.Read())
  {
   foreach (DataRow row in ds.Tables["Products"].Rows)
   {
     DuePaymentstring.Add(row["DuePayment"].ToString());
     DuePayment = DuePaymentstring.Select(x => double.Parse(x)).ToList();
   }
  }
  tdp = 0;
  tdp = DuePayment.Sum();                        
  DuePaymentstring.Remove(Convert.ToString(DuePaymentstring.Count));
  DuePayment.Clear();
 }
 cnn.Close();
 label3.Text = Convert.ToString(tdp + " Due Payment Count: " + 
 DuePayment.Count + " Due Payment string Count: " + DuePaymentstring.Count);
 tdp = 0;
 //DuePaymentstring.RemoveRange(0,DuePaymentstring.Count);
 //DuePayment.RemoveRange(0, DuePayment.Count);
 //Search and Calculate

这里的"varquery"是生成您通过搜索变量给出的搜索条件。然后"DuePaymentstring.Select"就是选择符合您给定条件的数据。如果您在理解方面有问题,请随时询问。