C# 如何在列表中找到特定元素<;T>;?

C# 如何在列表中找到特定元素<;T>;?,c#,list,properties,find,C#,List,Properties,Find,我的应用程序使用如下列表: List List=新列表() 使用Add方法,将MyClass的另一个实例添加到列表中 MyClass提供了以下方法: public void SetId(String Id); public String GetId(); 如何使用GetId方法查找MyClass的特定实例?我知道有Find方法,但我不知道这在这里是否有效 使用lambda表达式 MyClass result = list.Find(x => x.GetId() == "xy&q

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

List List=新列表()

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

MyClass
提供了以下方法:

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

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

使用lambda表达式

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

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

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

由于经常使用这种模式,C#提供了。它们是上述代码的简短版本;但是,支持变量是隐藏的且不可访问(但是,它可以从VB中的类中访问)

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

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
,但不能从外部设置。如果还需要在派生类中设置它,还可以保护setter

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-only属性。与使用私有setter自动实现的属性不同,Getter-only自动属性是只读属性

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

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); } }
请参阅:

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

public string Name
{
    get => _name;                                // getter
    set => _name = value;                        // setter
}
注意,在这种情况下,setter必须是一个表达式。它不能是一个声明。上面的例子很有效,因为在C#中,赋值可以用作表达式或语句。赋值表达式的值是指赋值本身是副作用的赋值。这允许您一次为多个变量赋值:
x=y=z=0
相当于
x=(y=(z=0))
并且与语句
x=0具有相同的效果;y=0;z=0

由于C#9.0,您可以使用只读(或者最好初始化一次)属性,这些属性可以在对象初始值设定项中初始化。对于仅getter属性,这目前是不可能的

public string Name { get; init; }

var c = new C { Name = "c-sharp" };
尝试:


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

MyClass found = list.Find(item => item.GetID() == ID);
您还可以使用扩展:

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

或者,如果您不喜欢使用,您可以采用传统的方式:

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
    }
}
List List=新列表();
foreach(列表中的MyClass元素)
{
if(element.GetId()=“这是你放在哪里的地方,你在找什么”)
{
break;//如果您只想找到第一个实例,则此处的break最适合您的应用程序
}
}
公共列表类别{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
var query=来自this.mJDBDataset.Products中的o
其中o.ProductStatus==textBox1.Text | | o.Karrot==textBox1.Text
||o.ProductDetails==textBox1.Text | | o.DepositDate==textBox1.Text
||o.SellDate==textBox1.Text
选择o;
dataGridView1.DataSource=query.ToList();
//搜索和计算
search=textBox1.Text;
cnn.Open();
字符串query1=string.Format(“从ProductStatus=”的产品中选择*”
+搜索+“'”;
SqlDataAdapter da=新的SqlDataAdapter(查询1,cnn);
数据集ds=新数据集();
da.填充(ds,“产品”);
SqlDataReader;
reader=newsqlcommand(query1,cnn).ExecuteReader();
列表付款=新列表();
if(reader.HasRows)
{
while(reader.Read())
{
foreach(ds.Tables[“Products”].Rows中的DataRow行)
{
添加(行[“DuePayment”].ToString());
DuePayment=DuePaymentstring.Select(x=>double.Parse(x)).ToList();
}
}
tdp=0;
tdp=DuePayment.Sum();
Remove(Convert.ToString(DuePaymentstring.Count));
DuePayment.Clear();
}
cnn.Close();
label3.Text=Convert.ToString(tdp+“到期付款计数:”+
DuePayment.Count+“到期付款字符串计数:”+DuePaymentstring.Count);
tdp=0;
//DuePaymentstring.RemoveRange(0,DuePaymentstring.Count);
//DuePayment.RemoveRange(0,DuePayment.Count);
//搜索和计算

这里的“var query”生成您通过搜索变量给出的搜索条件。然后“DuePaymentstring.Select”选择与给定条件匹配的数据。请随时询问您是否有理解问题

或者First的另一个重载:
MyClass result=list.First(m=>m.GetId()==id)很好的答案,谢谢。对于db操作,它看起来是这样的:
IQueryable result=db.Set().Find(//just id here//).ToList()它可能已经知道您正在寻找主键。仅供参考。我知道这是一个旧答案,但我会将get和set分离到不同的方法中,以便在比较过程中不会意外设置值。@JoelTrauger:比较读取属性,因此只调用getter。这是
 list.Find(item => item.id==myid);
MyClass found = list.Find(item => item.GetID() == ID);
string id = "hello";
MyClass result = list.Where(m => m.GetId() == id).First();
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
    }
}
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