ListLinq篩選數據

linq用法如下:
List<String> list = new List<String>();
                var q = from String s in list
                        where s[0] = "A" && s.Length = 4 //字符串是以A開頭,並且長度爲4位的 
                        select s;
q就是篩選後的結果

下面舉例說明List<T>的用法。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        public class Student //學生類作爲數據源
        {
            public string Name { get; set; }
            public List<int> Scores { get; set; } //成績集合
        }
        static void Main(string[] args)
        {
            //初始化泛型類List<Student>,集合中的元素包含一個成績的內部序列List<int>
            List<Student> students = new List<Student>();
            students.Add(new Student { Name = "張三", Scores = new List<int> { 93, 72, 88, 78 } });
            students.Add(new Student { Name = "李四", Scores = new List<int> { 95, 71, 88, 68 } });
            //使用Linq查詢
            var Query = from student in students
                        where student.Scores.Average() >= 80
                        select new
                        {
                            姓名 = student.Name,
                            成績 = student.Scores.Average()
                        };
            foreach (var q in Query)
                Console.WriteLine("{0} {1}", q.姓名, q.成績);
            Console.ReadLine();
        }
    }
}

輸出:張三 82.75 / 李四 80.5
發佈了65 篇原創文章 · 獲贊 59 · 訪問量 28萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章