0
点赞
收藏
分享

微信扫一扫

c# List集合举例十二种数据处理用法

浮游图灵 2023-06-29 阅读 61
c#listlinq

Person类:

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;
    }
}

请注意,这只是一个简单的示例类,实际场景中可能需要更复杂的属性和方法。

  1. 过滤List集合的对象,只保留sex为0的对象,并返回一个新的集合。
List<Person> people = new List<Person>(); // Person为自定义类,包含属性name和sex
List<Person> filteredPeople = people.Where(p => p.sex == 0).ToList();
  1. 找出符合条件的第一个对象,没有返回null。
Person firstPerson = people.FirstOrDefault(p => p.name == "John");
  1. 根据性别对集合进行分组,返回Map集合,每种性别个对应一个集合。
Dictionary<int, List<Person>> groupedPeople = people.GroupBy(p => p.sex).ToDictionary(g => g.Key, g => g.ToList());
  1. 从集合中抽出对象的某一属性,并创建一个新的集合。
List<string> names = people.Select(p => p.name).ToList();
  1. 从集合中抽出对象的某一属性,并创建一个新的集合,同时保证不重复。
List<Person> people = new List<Person>();
// 假设Person类包含name属性
HashSet<string> uniqueNames = new HashSet<string>();
foreach (Person person in people)
{
    uniqueNames.Add(person.name);
}
  1. 获取集合中符合条件的对象,如果存在,并做一些事情。
Person person = people.FirstOrDefault(p => p.name == "John");
if (person != null)
{
    // do something
}
  1. 从集合里匹配、或不匹配符合条件的对象属性,返回布尔值。
bool hasJohn = people.Any(p => p.name == "John");
bool allMales = people.All(p => p.sex == 0);
  1. 给一个对象,返回一个集合。
List<Person> singlePersonList = new List<Person>() { person };
  1. 抽取、排序、过滤、遍历组合使用。
List<Person> sortedPeople = people.Where(p => p.sex == 0).OrderBy(p => p.name).ToList();
foreach (Person person in sortedPeople)
{
    // do something
}
  1. Collectors工具类的使用汇总。

C#中没有Collectors工具类,但可以使用LINQ进行类似的操作。

  1. 求和,和10的求和有点区别。
int sumOfAges = people.Sum(p => p.age);
  1. 字符串数组,转为不重复集合。
string[] names = { "John", "Mary", "John" };
HashSet<string> uniqueNames = new HashSet<string>();
foreach (string name in names)
{
    uniqueNames.Add(name);
}
举报

相关推荐

0 条评论