LINQ to SQL收藏

暖楓無敵發表於2012-11-28

1、LINQ group by分組彙總

public class TestData  
{  
       public string Name{get;set;}  
        public int Count { get; set; }  
        public string BatNum { get; set; }  
}
protected void Click(object sender, EventArgs e)  
{  
        List<TestData> list = new List<TestData>();  
        list.Add(new TestData() { Name = "A", Count = 3, BatNum = "001" });  
        list.Add(new TestData() { Name = "A", Count = 3, BatNum = "001" });  
        list.Add(new TestData() { Name = "A", Count = 3, BatNum = "002" });  
        list.Add(new TestData() { Name = "b", Count = 3, BatNum = "001" });  
        list.Add(new TestData() { Name = "b", Count = 6, BatNum = "002" });  
        list.Add(new TestData() { Name = "b", Count = 3, BatNum = "003" });  
        list.Add(new TestData() { Name = "b", Count = 5, BatNum = "001" });  
        var query = from l in list  
                    group l by new { l.Name, l.BatNum } into g  
                    select new  
                    {  
                        Name = g.Key.Name,  
                        Count = g.Sum(a => a.Count),  
                        BatNum = g.Key.BatNum  
                    };  
        string result = "";  
        foreach (var q in query)  
        {  
            result += "Name=/"" + q.Name + "/"," + "Count=/"" + q.Count + "/"," + "BatNum=/"" + q.BatNum + " /"<br />";  
        }  
        Response.Write(result);  
}  
 //結果:   
Name="A",Count="6",BatNum="001 "  
Name="A",Count="3",BatNum="002 "  
Name="b",Count="8",BatNum="001 "  
Name="b",Count="6",BatNum="002 "  
Name="b",Count="3",BatNum="003 "  


 2、

 

相關文章