如何在List <t>中找到特定元素?</t>

时间:2012-03-24 19:43:17

标签: c# list properties find

我的应用程序使用如下列表:

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

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

MyClass提供了以下方法:

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

如何通过MyClass方法找到GetId的特定实例?我知道有Find方法,但我不知道这是否适用于此?!

8 个答案:

答案 0 :(得分:219)

使用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#提供auto-implemented properties。它们是上面代码的简短版本;但是,后备变量是隐藏的,不可访问(但是可以从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; } 。如果你需要在派生类中设置它,你也可以保护setter

virtual

最后,您可以将属性声明为public string Id { get; } = "A07"; // Evaluated once when object is initialized. 并在派生类中覆盖它们,从而允许您为getter和setter提供不同的实现;就像普通的虚拟方法一样。


从C#6.0(Visual Studio 2015,Roslyn)开始,您可以使用内联初始化程序编写仅具有getter的自动属性

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

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

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

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

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

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

请参阅:.NET Compiler Platform ("Roslyn")
New Language Features in C# 6

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

x = y = z = 0

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

答案 1 :(得分:18)

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

答案 2 :(得分:9)

尝试:

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

答案 3 :(得分:4)

您还可以使用LINQ扩展程序:

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

答案 4 :(得分:4)

或者,如果您不想使用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
    }
}

答案 5 :(得分:3)

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

MyClass found = list.Find(item => item.GetID() == ID);

答案 6 :(得分:0)

public List<DealsCategory> DealCategory { get; set; }
int categoryid = Convert.ToInt16(dealsModel.DealCategory.Select(x => x.Id));

答案 7 :(得分:0)

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

 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

此处“ var query”正在生成您通过搜索变量给出的搜索条件。然后,“ DuePaymentstring.Select”将选择与给定条件匹配的数据。随意询问您是否对理解有疑问。

相关问题