[英]How can I find a specific element in a List<T>?
我的應用程序使用這樣的列表:
List<MyClass> list = new List<MyClass>();
使用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 中可能習慣的那樣),而是編寫
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-only 屬性。 Getter-only 自動屬性是真正的只讀屬性,與具有私有 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))
並且與語句x = 0; y = 0; z = 0;
具有相同的效果x = 0; y = 0; z = 0;
x = 0; y = 0; z = 0;
.
從 C# 9.0 開始,您可以使用可以在對象初始值設定項中初始化的只讀(或更好的初始化一次)屬性。 目前這對於僅使用 getter 的屬性是不可能的。
public string Name { get; init; }
var c = new C { Name = "c-sharp" };
從 C# 10.0(2021 年 11 月)開始,我們可以使用 new field
關鍵字訪問自動創建的支持字段。
// Removes time part in setter
public DateTime HiredDate { get; init => field = value.Date(); }
var list = new List<MyClass>();
var item = list.Find( x => x.GetId() == "TARGET_ID" );
或者如果只有一個並且您想強制執行諸如SingleOrDefault
類的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
這里“var query”正在生成您通過搜索變量提供的搜索條件。 然后“DuePaymentstring.Select”正在選擇符合您給定條件的數據。 如果您在理解上有問題,請隨時提問。
console.writeline(“ Hello world”);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.