Linq学习

来源:互联网 发布:中国移动网络制式 编辑:程序博客网 时间:2024/05/19 18:00
 protected void Page_Load(object sender, EventArgs e)        {            string bb = "<a href=\"http://www.baidu.com\">百度</a><Br />";            Response.Write(bb);            IList<string> list = new List<string>()            {                "One", "Two", "Three", "Four",                  "Five", "Six", "Seven"              };            #region            /*1.             * Where 和Select是两个定义在Ienumerable<TSource>接口中非常重要的方法.它们的定义如下:              * public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)              * public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, int, bool> predicate)             * 所以任何来源于Ienumerable<TSource>接口的数据结构都能访问这个方法             *              * var numbersLengthThree = list.Where(x => x.Length == 3).Select(x => x).ToList();               numbersLengthThree.ForEach(x => Response.Write(x + "<br />"));             */            /*2.             * All 这个方法确定是否所有元素序列都满足某种条件,如果每一个元素都可以满足设定的特殊条件或者它是空,则方法返回true,否则返回false             * 定义如下:             * public static bool All<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)              *              * if (list.All(x => x.Length >= 3))                   Response.Write("All numbers have at least three characters. ");             */            /*3.             * Any 这个方法确定序列中的元素是否存在或者满足某种特定的条件。方法定义如下:             * public static bool Any<TSource>(this IEnumerable<TSource> source)              * public static bool Any<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)              * 第一种重载会找出元素序列是否包含元素, 第二种重载将会找出序列中是否有满足条件的元素             *              * if (list.Any())                   Response.Write("The sequence contains item.");             *              * if (list.Any(x => x.Length >= 3))                   Response.Write("The sequence contains at least a item which has three or more characters.");             */            #endregion            IList<int> listNumber = new List<int>()            {                 1,2,3,4,5,6,7,8,9,10             };            #region            /*4.             * Average 方法会计算在序列中的数字的平均值,这个方法的定义如下:              * public static double Average(this IEnumerable<int> source)              * public static decimal Average<TSource>(this IEnumerable<TSource> source, Func<TSource, decimal> selector)              *              * //  55/10=5.5               Response.Write(string.Format("Average of the numbers :{0}", listNumber.Average()));               //  2,4,6,8,10 =>30/5=6 =>6*2=12               Response.Write(                   string.Format("Average of the original numbers x2 :{0}",                   listNumber.Where<int>(x => x % 2 == 0).Select(x => x).Average(x => x * 2))               );             */            #endregion            /*5.              * Concat 这个方法的作用是连接(拼接)两个序列,它和Union不同,Union则返回序列中不重复(独一无二)的元素             * 而Concat返回序列中所有的原始元素,这个方法的定义如下:              * public static IEnumerable<TSource> Concat<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second)              *              *              * Contains 是否包含有个或符合某条件的元素;             * Count 获取或获取符合某条件的元素个数;             * Distinct 去掉重复或符合某条件的重复元素;(  Distict是用来排除相同序列中元素的,对于基础类型,可以直接使用Distinct)             * ElementAt 在序列(集合)中,这个方法返回一个特定索引的一个元素;              * Except 方法可以用在从一个集合中删除一个项集合.它放回一个由两个序列产生的集合差;             * Intersect 它将产生两个序列的交集;             * First 这个方法会返回序列中的第一个元素;             * FirstOrDefault 它返回序列中第一个元素或者当没有元素未被找到时放回默认值.这个方法是First和Default的综合;             * Last 返回序列中最后一个元素;             * LastOrDefault 它返回序列中最后一个元素或者当没有元素未被找到时放回默认值.这个方法是Last和Default的综合;             *              *              * LongCount 它会返回一个Int64去表示序列中元素的个数,方法定义是:              * public static long LongCount<TSource>(this IEnumerable<TSource> source)              * public static long LongCount<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)              *              */            IList<int> tempList = new List<int>()            {                11,12,13,2,5,12,13            };            #region            //Linq查询表达式中提供了join运算,比较常见的是join.. on ..equals,也就是内联接运算            //下面的demo相当于交集运算Intersect            var do_join = from itemsA in tempList                          join itemsB in listNumber                          on itemsA equals itemsB into tempArr                          from arr in tempArr                          select arr;            do_join.ToList().ForEach(x => Response.Write("join运算" + x + "&emsp;"));            Response.Write("<br />");            listNumber.Concat(tempList).ToList().ForEach(x => Response.Write(x + " , "));            Response.Write("<br />");            listNumber.Union(tempList).ToList().ForEach(x => Response.Write(x + " , "));            Response.Write("<br />");            Response.Write(string.Format("大于7的元素个数为{0}", listNumber.Count<int>(s => s > 7)));            Response.Write("<br />");            tempList.Distinct<int>().Select(x => x).ToList().ForEach(x => Response.Write(x + " , "));            //但是对于自定义类型,则需要额外的一些操作,方式有多种,这里选择其中一种,即实现IEquatable<>            List<Employee> employee = new List<Employee>()            {                new Employee {Id= 1, Name = "Ringgo"},                new Employee {Id= 2, Name = "Rex"},                new Employee {Id = 1, Name = "jj"}            };            employee.Distinct().ToList().ForEach(x => Response.Write("&emsp;" + x.Id + ":" + x.Name));            Response.Write("<br />");            Response.Write(tempList.Where(x => x % 2 == 1).Select(x => x).ToList().ElementAt(1).ToString()); //所有奇数元素集合中第二个元素            Response.Write("<br />");            IList<Person> personA = new List<Person>()            {                new Person{Name="jon",Address="hangzhou"},                new Person{Name="aa",Address="shanghai"},                new Person{Name="tt",Address="hangzhou"},                new Person{Name="gg",Address="hangzhou"}            };            IList<Person> personB = new List<Person>()            {                new Person{Name="aa",Address="beijing"},                new Person{Name="dd",Address="shenzhen"}            };            var resultPerson = (from p in personA select p.Name).Except(from q in personB select q.Name).ToList();            resultPerson.ForEach(x => Response.Write(x + " , "));            Response.Write("<br />");            tempList.Except(listNumber).ToList().ForEach(x => Response.Write(x + " , ")); //差集(减去另一个集合中包含的元素,如果没有包含就全部输出,有就去掉)            Response.Write("<br />");            tempList.Intersect(listNumber).ToList().ForEach(x => Response.Write(x + " , ")); //交集(两个集合共有的元素)            Response.Write("<br />");            #endregion            /*6.             *Contains 这个方法用来判断在一个序列(集合)中是否存在一个特殊的元素             *public static bool Contains<TSource>(this IEnumerable<TSource> source, TSource value)             *public static bool Contains<TSource>(this IEnumerable<TSource> source, TSource value, IEqualityComparer<TSource> comparer)              *             * Response.Write(string.Format("{0}\t{1}", tempList.Contains(2).ToString(), tempList.Contains(200).ToString()));             */            /*7.             * DefaultIfEmpty 这个方法会返回一个IEnumerable<T>类型的元素或者当序列(集合)为空事放回一个默认的单例集合.方法的定义如下:              * public static IEnumerable<TSource> DefaultIfEmpty<TSource>(this IEnumerable<TSource> source)              * public static IEnumerable<TSource> DefaultIfEmpty<TSource>(this IEnumerable<TSource> source, TSource defaultValue)              *              *              */            #region            List<Product> products = new List<Product>()            {                new Product(){ Id="1", Name="n1"},                new Product(){ Id="1", Name="n2"},                new Product(){ Id="2", Name="n1"},                new Product(){ Id="2", Name="n2"},            };            var ggresult = products.GroupBy(p => p.Id).Select(p => new            {                Id = p.Key,                Name = p.FirstOrDefault().Name            });            ggresult.ToList().ForEach(v =>            {                Response.Write(v.Id + ":" + v.Name + "&emsp;");            });            #endregion        }        public class Product        {            public string Id { get; set; }            public string Name { get; set; }        }        public class Employee : IEquatable<Employee>        {            public int Id { get; set; }            public string Name { get; set; }            public bool Equals(Employee other)            {                try                {                    if (Object.ReferenceEquals(other, null))                        return false;                    if (Object.ReferenceEquals(this, other))                        return true;                    return Id.Equals(other.Id);                }                catch                {                    throw new NotImplementedException();                }            }            /// <summary>            ///  这里重写了GetHashCode,Equals根据ID相同过滤对象            /// </summary>            public override int GetHashCode()            {                return Id.GetHashCode();            }        }        public class Person        {            public string Name { get; set; }            public string Address { get; set; }        }


Find和FindAll的区别,Find找到第一个匹配项就结束了,而FindAll会去找所有符合的匹配对象

 string[] arry = { "aa", "bb", "cc", "aabb" };            //var t = arry.ToList().Find(x => x.Contains("aa")); //只有aa            var t = arry.ToList().FindAll(x => x.Contains("aa")); //aa和aabb            t.ToList().ForEach(x => Response.Write(x + ", "));


原创粉丝点击