简体   繁体   English

按属性在列表中查找项目并知道项目名称

[英]Find item in list by property and know the item name

I have struggled with figuring out how to find an item in a list by checking for a property and then isolating and naming this item. 我一直在努力寻找如何在列表中找到一个项目,方法是检查属性,然后隔离并命名该项目。 I need to do this to set a value that corresponds with that specific string. 我需要这样做以设置与该特定字符串相对应的值。 It wouldn't work if I just found that there is one, or several items in the list that match the property. 如果我只是发现列表中有一个或多个与该属性相匹配的项目,那将是行不通的。 My code is massive, but here's a snippet of it: 我的代码很多,但是下面是它的一个片段:

List<string> diag_right = new List<string>();
diag_right.Add(b3); //Add the string b3
diag_right.Add(b5); //Add the string b5
diag_right.Add(b7); //Add the string b7

if (diag_right.Exists(a => a.Equals("")))
{
    //Find the item (string name, b3, b5, etc.) that was found as matching the blank property
}

Is it possible to do this? 是否有可能做到这一点? I know I can do this by checking to see if each string matches this property individually, but is there a faster way to do this? 我知道我可以通过检查每个字符串是否分别匹配此属性来做到这一点,但是有没有更快的方法呢?

Many ways this can be achieved, I prefer simple approach, loop collection using index and modify matching field 这可以通过多种方式实现,我更喜欢简单的方法,使用索引进行循环收集并修改匹配字段

for(int index=0; index< diag_right.Count(); index++)
{
    if(diag_right[index] == "b3")
    {
        // update               
        diag_right[index] = "b8";               
    }
}

Linq approach Linq方法

This approach I just used Linq to fetch all indexes for a matching string. 我只是使用Linq这种方法来获取匹配字符串的所有索引。

var indexes = diag_right.Where(e=>e.Equals("searchstring")).Select((c,i) => i).ToList();

foreach(int index in indexes) // loop through each line.
{
     diag_right[index] = "newvalue"; // set new value.
}

Working Demo 工作Demo

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM