如何在 List<T> 中找到特定元素? [英] How can I find a specific element in a List&lt;T&gt;?

查看:36
本文介绍了如何在 List<T> 中找到特定元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

My application uses a list like this:

Listlist = new List();

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

Using the Add method, another instance of MyClass is added to the list.

MyClass 提供以下方法:

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

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

How can I find a specific instance of MyClass by means of using the GetId method? I know there is the Find method, but I don't know if this would work here?!

推荐答案

使用 lambda 表达式

Use a lambda expression

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


注意:C# 具有内置的属性语法.与其将 getter 和 setter 编写为普通方法(就像您在 Java 中可能习惯的那样),而是编写


Note: C# has a built-in syntax for properties. Instead of writing getter and setter as ordinary methods (as you might be used to from Java), write

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

value 是仅在 set 访问器中已知的上下文关键字.它代表分配给属性的值.

value is a contextual keyword known only in the set accessor. It represents the value assigned to the property.

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

Since this pattern is often used, C# provides auto-implemented properties. They are a short version of the code above; however, the backing variable is hidden and not accessible (it is accessible from within the class in VB, however).

public string Id { get; set; }

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

You can simply use properties as if you were accessing a field:

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


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


Using properties, you would search for items in the list like this

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


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


You can also use auto-implemented properties if you need a read-only property:

public string Id { get; private set; }

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

This enables you to set the Id within the class but not from outside. If you need to set it in derived classes as well you can also protect the setter

public string Id { get; protected set; }


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


And finally, you can declare properties as virtual and override them in deriving classes, allowing you to provide different implementations for getters and setters; just as for ordinary virtual methods.

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

Since C# 6.0 (Visual Studio 2015, Roslyn) you can write getter-only auto-properties with an inline initializer

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

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

You can also initialize getter-only properties within the constructor instead. Getter-only auto-properties are true read-only properties, unlike auto-implemented properties with a private setter.

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

This works also with read-write auto-properties:

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

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

Beginning with C# 6.0 you can also write properties as expression-bodied members

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 都可以用表达式体编写:

Starting with C# 7.0, both, getter and setter, can be written with expression bodies:

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;.

Note that in this case the setter must be an expression. It cannot be a statement. The example above works, because in C# an assignment can be used as an expression or as a statement. The value of an assignment expression is the assigned value where the assignment itself is a side effect. This allows you to assign a value to more than one variable at once: x = y = z = 0 is equivalent to x = (y = (z = 0)) and has the same effect as the statements x = 0; y = 0; z = 0;.

从 C# 9.0 开始,您可以使用只读(或更好的初始化一次)属性,您可以在对象初始值设定项中对其进行初始化.目前这对于仅使用 getter 的属性是不可能的.

Since C# 9.0 you can use read-only (or better initialize-once) properties that you can initialize in an object initializer. This is currently not possible with getter-only properties.

public string Name { get; init; }

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

讨论了 C# 未来版本的一个特性:field 关键字,允许访问自动创建的支持字段.

A feature is discussed for a future version of C#: The field keyword allowing the access to the automatically created backing field.

// Removes time part in setter
public DateTime HiredDate { get; init => field = value.Date(); }

这篇关于如何在 List<T> 中找到特定元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆