Lambda 的记录

Posted by 梁小生 on 2019-01-23

Java中的Lambda的使用

  • filter返回序列中满足条件的元素集合

    // 从集合中返回Name等于"liang"的集合
    List<User> userListOrderBy= userList.stream().filter((User u) -> u.getName().equals("liang")).collect(Collectors.toList());
    
  • sort 集合排序

    // 将集合已No字段升序排序,若是要降序 user2.getNo() - user1.getNo() 即可
    Collections.sort(userList,(user1, user2) -> user1.getNo() - user2.getNo());
    

C# 中常用Lambda和Linq结合

  • C# FirstOrDefault(),返回序列中满足条件的第一个元素;如果未找到这样的元素,则返回null

    // 从集合中返回Value为"1", IconKey
    var obij = FuncCache.FirstOrDefault(p => p.Value == "1" && p.IconKey == "2");
    
  • C# Where(),从集合中挑出符合条件的多个项

    // 将BranchNoOption集合中的EnableStatus字段为'1'的集合挑选出来
    BranchNoOption = new ObservableCollection<F120061_Info>(BranchNoOption.Where(p => p.EnableStatus == '1'));
    
  • C# OrderBy()、OrderByDescending(),将集合按某个字段进行升序或者降序排序

    // 将workFlowDtoList集合按AuditLevel字段升序排序
    workFlowDtoList = new List<WorkFlowDto>(workFlowDtoList.OrderBy(s => s.AuditLevel));
    
  • C# GroupBy(),集合元素分组

    // studentGroup 为按studentList按ClassName分类好的集合
    var studentGroup = studentList.GroupBy(s => s.ClassName);
    
  • C# Select(),挑选出集合中的字段的值变成一个:挑选出字段的新集合

    // branchNoList 为按F360576_InfoList挑选出的所有BranchNo集合
    var branchNoList = F360576_InfoList.Select(s=>s.BranchNo);
    
  • C# 中Where扩展

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    // 挑选出集合中名称不为1或者2的

    public void Test()
    {
    var testList = new ObservableCollection<MyClass>();

    for (int i = 0; i < 1000; i++)
    {
    var test = new MyClass();
    test.Name = i.ToString();
    test.Value = i.ToString();
    testList.Add(test);
    }

    var listTemp = testList.Where(s => !"1,2".Contains(s.Name)).ToList();
    }