Person
類(lèi):
public class Person
{
public string name;
public int sex; // 0表示男性,1表示女性
public int age;
public Person(string name, int sex, int age)
{
this.name = name;
this.sex = sex;
this.age = age;
}
}
請(qǐng)注意,這只是一個(gè)簡(jiǎn)單的示例類(lèi),實(shí)際場(chǎng)景中可能需要更復(fù)雜的屬性和方法。文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-513218.html
- 過(guò)濾List集合的對(duì)象,只保留sex為0的對(duì)象,并返回一個(gè)新的集合。
List<Person> people = new List<Person>(); // Person為自定義類(lèi),包含屬性name和sex
List<Person> filteredPeople = people.Where(p => p.sex == 0).ToList();
- 找出符合條件的第一個(gè)對(duì)象,沒(méi)有返回null。
Person firstPerson = people.FirstOrDefault(p => p.name == "John");
- 根據(jù)性別對(duì)集合進(jìn)行分組,返回Map集合,每種性別個(gè)對(duì)應(yīng)一個(gè)集合。
Dictionary<int, List<Person>> groupedPeople = people.GroupBy(p => p.sex).ToDictionary(g => g.Key, g => g.ToList());
- 從集合中抽出對(duì)象的某一屬性,并創(chuàng)建一個(gè)新的集合。
List<string> names = people.Select(p => p.name).ToList();
- 從集合中抽出對(duì)象的某一屬性,并創(chuàng)建一個(gè)新的集合,同時(shí)保證不重復(fù)。
List<Person> people = new List<Person>();
// 假設(shè)Person類(lèi)包含name屬性
HashSet<string> uniqueNames = new HashSet<string>();
foreach (Person person in people)
{
uniqueNames.Add(person.name);
}
- 獲取集合中符合條件的對(duì)象,如果存在,并做一些事情。
Person person = people.FirstOrDefault(p => p.name == "John");
if (person != null)
{
// do something
}
- 從集合里匹配、或不匹配符合條件的對(duì)象屬性,返回布爾值。
bool hasJohn = people.Any(p => p.name == "John");
bool allMales = people.All(p => p.sex == 0);
- 給一個(gè)對(duì)象,返回一個(gè)集合。
List<Person> singlePersonList = new List<Person>() { person };
- 抽取、排序、過(guò)濾、遍歷組合使用。
List<Person> sortedPeople = people.Where(p => p.sex == 0).OrderBy(p => p.name).ToList();
foreach (Person person in sortedPeople)
{
// do something
}
- Collectors工具類(lèi)的使用匯總。
C#中沒(méi)有Collectors工具類(lèi),但可以使用LINQ進(jìn)行類(lèi)似的操作。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-513218.html
- 求和,和10的求和有點(diǎn)區(qū)別。
int sumOfAges = people.Sum(p => p.age);
- 字符串?dāng)?shù)組,轉(zhuǎn)為不重復(fù)集合。
string[] names = { "John", "Mary", "John" };
HashSet<string> uniqueNames = new HashSet<string>();
foreach (string name in names)
{
uniqueNames.Add(name);
}
到了這里,關(guān)于c# List集合舉例十二種數(shù)據(jù)處理用法的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!