如何检查列表中是否存在值?

时间:2022-09-12 04:28:38

I'm relatively new to C# programming (programming as a whole, actually), but I've built an application to manage the application pools on a server that my team at work uses. It does everything it's supposed to fairly well, but the only issue I'm running into is in saving previously-used configurations to the app.config file so the user doesn't have to put them in manually every time. As it stands, I can save to and load from the file magnificently (along with all of the strings I need in each group).

我对C#编程比较陌生(实际上是整个编程),但是我已经构建了一个应用程序来管理我工作的团队使用的服务器上的应用程序池。它完成了它应该做得很好的一切,但我遇到的唯一问题是将以前使用的配置保存到app.config文件中,这样用户就不必每次都手动将它们放入。就目前而言,我可以保存并从文件中加载(以及每组中我需要的所有字符串)。

The issue is that I want to do a cursory check to see if a Name string exists in the group before writing it. Example of the part of the app.config:

问题是我想在进行粗略检查之前查看组中是否存在Name字符串。 app.config部分的示例:

<appSettings>
 <add Name="RowName" MachineName="MS-02348" AppSrvName="AppServer" WebSrvName="AppNet"/>
 <add Name="RowName2" MachineName="MS-68186" AppSrvName="AppServer2" WebSrvName="AppNet2"/>
</appSettings>

So what I'm currently doing to load the values is I have a method that retrieves the appSettings/add nodes and throws them into a list, then sets the values to properties of an object. The reason I do this is so that I can have a drop-down that lists only the Name of an object, and then the rest of the information is all available for when I call the method on the selected item.

所以我目前正在做的加载值的方法是我有一个方法来检索appSettings / add节点并将它们抛出到列表中,然后将值设置为对象的属性。我这样做的原因是我可以有一个仅列出对象名称的下拉列表,然后当我在所选项目上调用方法时,其余信息都可用。

Anyway, what I'm running into now is that I want to make sure that if the Name already exists in the app.config, I prompt the user to write another name instead of saving it to the database. Having two child nodes with the same "Name" value would wreak havoc on my logic.

无论如何,我现在遇到的是,我想确保如果名称已经存在于app.config中,我会提示用户写另一个名称而不是将其保存到数据库中。拥有两个具有相同“名称”值的子节点会对我的逻辑造成严重破坏。

I tried a foreach to cycle through the objects in the list, but without knowing how many objects there could be I didn't know of an easy way of really saying it does or does not exist. I've also tried targeting the childnode based on the values listed in the node, but it seems to fail there too. I'm guessing that part is syntax, but it seems to match up with how the method list defines it.

我试过一个foreach循环遍历列表中的对象,但是不知道有多少个对象我不知道一个简单的方法,真正说它确实存在或不存在。我也尝试根据节点中列出的值来定位子节点,但它似乎也失败了。我猜这部分是语法,但它似乎与方法列表定义它的方式相匹配。

Any thoughts?

3 个解决方案

#1


7  

if (list.Any()) 
{ 
   // found something! 
}
else 
{
   // found nothing 
}

I always use Any() simply because it's the most performant. List.Count() goes through each item and counts them, but you don't care about the number of items -- you only care if there's an item at all. Any() will enumerate through the list and stop if it finds an item. So, in the extreme case, in a list of a million items Count() will enumerate every single one and return while Any() will enumerate one and return.

我总是使用Any()只是因为它是最高效的。 List.Count()遍历每个项目并计算它们,但你不关心项目的数量 - 你只关心是否有一个项目。 Any()将枚举列表并在找到项目时停止。因此,在极端情况下,在一百万个项目的列表中,Count()将枚举每一个项目并返回,而Any()将枚举一个并返回。

Plus, it returns a bool, which is handy for more concise code. :)

此外,它返回一个bool,这对于更简洁的代码很方便。 :)

As an added bonus, you can call Any() looking for specific things. So, in a list of people I can look to see if there are any people older than 21 in it:

作为额外的奖励,你可以调用Any()寻找特定的东西。因此,在一个人列表中,我可以查看是否有任何超过21岁的人:

if (list.Any(person => person.Age > 21))
{
   // ...
}

Edit: Formatting.

#2


5  

maybe something like this

也许这样的事情

        var list = new List<AppSettings>();
        var item = list.FirstOrDefault(x => x.Name == NameEnteredByUser);
        if (item == null)
        {
            //there is no such item
        }
        else
        {
           //notify the user
        }

or the Any extension method:

或任何扩展方法:

 var list = new List<AppSettings>();
        if (list.Any(x => x.Name == NameEnteredByUser))
        {
            //name exists
        }
        else
        {
            //no such name used before
        }

As a sidenote, have a unique field configured in your database so that when your programming logic fails you wont enter a record. corrupt data state in db is bad.

作为旁注,在数据库中配置了一个唯一的字段,以便在编程逻辑失败时不会输入记录。 db中的损坏数据状态很糟糕。

#3


0  

neo112 is correct in his logic, but I am unsure if the main problem you have is performance related, since you mention you dont know if it may get too long.

neo112在他的逻辑中是正确的,但我不确定你的主要问题是否与性能有关,因为你提到你不知道它是否会变得太长。

First, you could also do the following;

首先,您还可以执行以下操作;

int count = list.Count(a => a.Name == NameEnteredByUser);
if(count > 0)
{
    // exists
}

I believe .Count() is faster than .First() (anecdotal evidence only) and personally think it's a bit cleaner.

我相信.Count()比.First()(只有轶事证据)快,并且个人认为它更清洁一些。

Also, another thing you could try to do is to sort your list by name when adding to the appSettings node. Then, you should instantiate a SortedList instead of just List, then that would also (possitively) affect performance. But, I am unsure if sorting is an option for you.

此外,您可以尝试做的另一件事是在添加到appSettings节点时按名称对列表进行排序。然后,您应该实例化SortedList而不仅仅是List,那么(也可能)会影响性能。但是,我不确定排序是否适合您。

#1


7  

if (list.Any()) 
{ 
   // found something! 
}
else 
{
   // found nothing 
}

I always use Any() simply because it's the most performant. List.Count() goes through each item and counts them, but you don't care about the number of items -- you only care if there's an item at all. Any() will enumerate through the list and stop if it finds an item. So, in the extreme case, in a list of a million items Count() will enumerate every single one and return while Any() will enumerate one and return.

我总是使用Any()只是因为它是最高效的。 List.Count()遍历每个项目并计算它们,但你不关心项目的数量 - 你只关心是否有一个项目。 Any()将枚举列表并在找到项目时停止。因此,在极端情况下,在一百万个项目的列表中,Count()将枚举每一个项目并返回,而Any()将枚举一个并返回。

Plus, it returns a bool, which is handy for more concise code. :)

此外,它返回一个bool,这对于更简洁的代码很方便。 :)

As an added bonus, you can call Any() looking for specific things. So, in a list of people I can look to see if there are any people older than 21 in it:

作为额外的奖励,你可以调用Any()寻找特定的东西。因此,在一个人列表中,我可以查看是否有任何超过21岁的人:

if (list.Any(person => person.Age > 21))
{
   // ...
}

Edit: Formatting.

#2


5  

maybe something like this

也许这样的事情

        var list = new List<AppSettings>();
        var item = list.FirstOrDefault(x => x.Name == NameEnteredByUser);
        if (item == null)
        {
            //there is no such item
        }
        else
        {
           //notify the user
        }

or the Any extension method:

或任何扩展方法:

 var list = new List<AppSettings>();
        if (list.Any(x => x.Name == NameEnteredByUser))
        {
            //name exists
        }
        else
        {
            //no such name used before
        }

As a sidenote, have a unique field configured in your database so that when your programming logic fails you wont enter a record. corrupt data state in db is bad.

作为旁注,在数据库中配置了一个唯一的字段,以便在编程逻辑失败时不会输入记录。 db中的损坏数据状态很糟糕。

#3


0  

neo112 is correct in his logic, but I am unsure if the main problem you have is performance related, since you mention you dont know if it may get too long.

neo112在他的逻辑中是正确的,但我不确定你的主要问题是否与性能有关,因为你提到你不知道它是否会变得太长。

First, you could also do the following;

首先,您还可以执行以下操作;

int count = list.Count(a => a.Name == NameEnteredByUser);
if(count > 0)
{
    // exists
}

I believe .Count() is faster than .First() (anecdotal evidence only) and personally think it's a bit cleaner.

我相信.Count()比.First()(只有轶事证据)快,并且个人认为它更清洁一些。

Also, another thing you could try to do is to sort your list by name when adding to the appSettings node. Then, you should instantiate a SortedList instead of just List, then that would also (possitively) affect performance. But, I am unsure if sorting is an option for you.

此外,您可以尝试做的另一件事是在添加到appSettings节点时按名称对列表进行排序。然后,您应该实例化SortedList而不仅仅是List,那么(也可能)会影响性能。但是,我不确定排序是否适合您。