C# traverse Dic, List

C# traverse dictionary

There is a C#的Dictionary<string,Hello>dictionary, find a certain attribute value, the code below is to find the code whose sex attribute of the hello object in the dictionary or List is false.

Dictionary<string, Hello> dict = new Dictionary<string, Hello>();

// 添加一些 Hello 对象到字典中
dict.Add("1", new Hello("John", true));
dict.Add("2", new Hello("Jane", false));
dict.Add("3", new Hello("Bob", false));

foreach (KeyValuePair<string, Hello> kvp in dict)
{
    if (!kvp.Value.sex)
    {
        Console.WriteLine("Found a Hello object with sex set to false:");
        Console.WriteLine("Key = {0}, Name = {1}, Sex = {2}", kvp.Key, kvp.Value.name, kvp.Value.sex);
    }
}
public class Hello
{
    public string name;
    public bool sex;
}

C# traverse List

some shared code

public class Hello
{
    public string name;
    public bool sex;

    public Hello(string name, bool sex)
    {
        this.name = name;
        this.sex = sex;
    }
}


List<Hello> helloList = new List<Hello>();
// 添加一些 Hello 对象到列表中
helloList.Add(new Hello("John", true));
helloList.Add(new Hello("Jane", false));
helloList.Add(new Hello("Bob", false));

use for

private void Dosomething()
{
	for (int i = 0; i < helloList.Count; i++)
	{
	    if (!helloList[i].sex)
	    {
   	    	   Console.WriteLine("Found a Hello object with sex set to false:");
	    	   Console.WriteLine("Name = {0}, Sex = {1}", helloList[i].name, helloList[i].sex);
	    }
	}
}

use foreach

foreach (Hello hello in helloList)
{
    if (!hello.sex)
    {
        Console.WriteLine("Found a Hello object with sex set to false:");
        Console.WriteLine("Name = {0}, Sex = {1}", hello.name, hello.sex);
    }
}

Using the List.Where method

List<Hello> falseSexHellos = helloList.Where(h => h.sex == false).ToList();
foreach (Hello hello in falseSexHellos)
{
    Console.WriteLine("Found a Hello object with sex set to false:");
    Console.WriteLine("Name = {0}, Sex = {1}", hello.name, hello.sex);
}

Method using List.FirstOrDefault

Hello firstFalseSexHello = helloList.FirstOrDefault(h => h.sex == false);
if (firstFalseSexHello != null)
{
    Console.WriteLine("Found the first Hello object with sex set to false:");
    Console.WriteLine("Name = {0}, Sex = {1}", firstFalseSexHello.name, firstFalseSexHello.sex);
}

Method using IEnumerable.Where

IEnumerable<Hello> falseSexHellos2 = helloList.Where(h => h.sex == false);
foreach (Hello hello in falseSexHellos2)
{
    Console.WriteLine("Found a Hello object with sex set to false:");
    Console.WriteLine("Name = {0}, Sex = {1}", hello.name, hello.sex);
}

Enjoy

Part of the code is generated by ChatGPT.

Guess you like

Origin blog.csdn.net/GoodCooking/article/details/129408622