zoukankan      html  css  js  c++  java
  • 关于list 和 IEnumerable 在lambd表达式的使用与注意

    例子1:
    using
    System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Linq.Expressions; using System.Windows; namespace WpfApplication1 { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> /// /// public partial class MainWindow : Window { List<Person> persons=new List<Person>(); public MainWindow() { InitializeComponent(); persons.Add(new Person() {Age = 1, Name = "A1"}); persons.Add(new Person() { Age = 2, Name = "A2" }); persons.Add(new Person() { Age = 3, Name = "A3" }); persons.Add(new Person() { Age = 4, Name = "A4" }); persons.Add(new Person() { Age = 5, Name = "A5" }); persons.Add(new Person() { Age = 5, Name = "A6" }); persons.Add(new Person() { Age = 5, Name = "A7" }); persons.Add(new Person() { Age = 6, Name = "A8" }); Loaded += Onload; } private void Onload(object sender, RoutedEventArgs e) { var lists = persons.Select(p => p.Age > 2 ? p : null).Where(p=>p!=null); foreach (var list in lists) { Debug.WriteLine(list.Name); } } } public class Person { public int Age { get; set; } public string Name { get; set; } } }
    例子2:
    using
    System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Linq.Expressions; using System.Windows; namespace WpfApplication1 { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> /// /// public partial class MainWindow : Window { List<Person> persons=new List<Person>(); public MainWindow() { InitializeComponent(); persons.Add(new Person() {Age = 1, Name = "A1"}); persons.Add(new Person() { Age = 2, Name = "A2" }); persons.Add(new Person() { Age = 3, Name = "A3" }); persons.Add(new Person() { Age = 4, Name = "A4" }); persons.Add(new Person() { Age = 5, Name = "A5" }); persons.Add(new Person() { Age = 5, Name = "A6" }); persons.Add(new Person() { Age = 5, Name = "A7" }); persons.Add(new Person() { Age = 6, Name = "A8" }); Loaded += Onload; } private void Onload(object sender, RoutedEventArgs e) { var lists = persons.Select(p => p.Age > 2 ? p : null).Where(p=>p!=null).ToList(); foreach (var list in lists) { Debug.WriteLine(list.Name); } } } public class Person { public int Age { get; set; } public string Name { get; set; } } }

    例子1和例子2区别在与lambda表达式后的.tolist();

    重点来了

    例子1中没有使用tolist所以当var lists = persons.Select(p => p.Age > 2 ? p : null).Where(p=>p!=null);

    lists是没有值的只有当进行foreach循环时才有值,而例子2,lists是一个list,这样就会有内存分配给lists而例子1则不会,

    总结当tolist有万条以上时要有例子1的写法,这样就会节省内存,但如果.select.......这个lambda表达式算法超复杂,那最后有例子2直接操作list来处理这样cpu的使用会减少很多。

  • 相关阅读:
    一天一个算法:将一个数组中的值按逆序输出
    一天一个算法:求俩个数的最大公约数和最小公倍数
    一天一个算法:给出年、月、日,计算该日是该年的第几天
    一天一个算法:递归计算函数
    一天一个算法:冒泡排序算法
    一天一个算法:猴子吃桃问题
    一天一个算法:求Sn=a+aa+aaa+…+aa…a之和
    一天一个算法:完数
    一天一个算法:水仙花数
    一天一个算法:前言
  • 原文地址:https://www.cnblogs.com/dzh1990/p/8251074.html
Copyright © 2011-2022 走看看