在类列表中查找类元素

发布于 2024-10-08 15:59:58 字数 475 浏览 1 评论 0原文

我正在尝试使用“List.Find”方法来查找与我的类中的元素的匹配项。这是一个例子......

class MyClass
{
    String item1;
    String item2;
}

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

// I am trying to find all instances of "MyClass" in the list "myClassList"
// where the element "item1" is equal to "abc"
// myClassList.Find(item => .item1 == "abc"); ?????

无论如何,我希望能解释得更好一些。我对最后一部分感到困惑,所以我的问题是:如何使用 List.Find 来查找类列表中元素的匹配项。

谢谢,如果我不清楚,请告诉我。

I am trying to use the "List.Find" method to find a match with an element in my class. Here is an example...

class MyClass
{
    String item1;
    String item2;
}

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

// I am trying to find all instances of "MyClass" in the list "myClassList"
// where the element "item1" is equal to "abc"
// myClassList.Find(item => .item1 == "abc"); ?????

Anyway, I hope that explains a bit better. I am confused about the last part, so my question is: How can I use List.Find to find matches of an element in a list of classes.

Thanks and please let me know if I'm not being clear.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

时光磨忆 2024-10-15 15:59:58

你的例子已经差不多了。您可能应该使用 FindAll 方法:

List<MyClass> results = myClassList.FindAll(x => x.item1 == "abc");

或者,如果您如果您希望将结果输入为 IEnumerable 而不是 List,您可以使用 LINQ 的 Where 方法:

IEnumerable<MyClass> results = myClassList.Where(x => x.item1 == "abc");

Your example is almost there. You should probably be using the FindAll method:

List<MyClass> results = myClassList.FindAll(x => x.item1 == "abc");

Or, if you prefer your results to be typed as IEnumerable<T> rather than List<T>, you can use LINQ's Where method:

IEnumerable<MyClass> results = myClassList.Where(x => x.item1 == "abc");
℉絮湮 2024-10-15 15:59:58

使用 where 扩展方法:

var items = myClassList.Where(x => x.item1 == "abc");

上面的代码片段将返回所有具有属性的对象item1 等于“abc”。

Use the where extension method:

var items = myClassList.Where(x => x.item1 == "abc");

The above snippet will return all objects with property item1 equal to "abc".

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文