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

3 篇文章 0 订阅
1 篇文章 0 订阅

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);
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值