用Lambda或者Linq语法对结果进行Group by并输出

        List lst_Attrib = new List();
        DataTable dt_Attrib = new DataTable();
        lst_Attrib = CategoryMapingBLL.GetModelList(9999, 1, "SP_CategoryID='" + dl_selectCategory.SelectedValue + "'", out count);
        if (lst_Attrib.Count == 0)
        {
            Response.Write("此类别中尚未添加属性选项。");
            return;
        }
        //Linq形式
        //var MainAttribList = from a in lst_Attrib
        //                     group a by a.SP_MapAttribID into l
        //                     select new { 
        //                         l.First().SP_MapAttribID
        //                     };
        //Lambda形式
        var MainAttribList = lst_Attrib.GroupBy(x => x.SP_MapAttribID).Select(a => new { a.First().SP_MapAttribID });

        foreach (var m in MainAttribList)
        {
            Response.Write(m.SP_MapAttribID + "
"); }

原结果:

SP_MapAttribID	SP_SubAttribID	SP_CategoryID
CO1001001	C0200003	CO300001501001
CO1001001	C0200002	CO300001501001
CO1001001	C0200001	CO300001501001
CO0901001	C0300002	CO300001501001
CO0901001	C0300001	CO300001501001
CO0801001	C0400003	CO300001501001
CO0801001	C0400002	CO300001501001
CO0801001	C0400001	CO300001501001
CO0701001	C0500001	CO300001501001
CO0601001	C0600001	CO300001501001
CO0501001	C0700001	CO300001501001
CO0401001	C0800002	CO300001501001
CO0401001	C0800001	CO300001501001
CO0301001	C0900001	CO300001501001
CO0201001	C1000001	CO300001501001
CO0101001	C0100005	CO300001501001
CO0101001	C0100004	CO300001501001
CO0101001	C0100003	CO300001501001
CO0101001	C0100002	CO300001501001
CO0101001	C0100001	CO300001501001

输出结果:

CO1001001
CO0901001
CO0801001
CO0701001
CO0601001
CO0501001
CO0401001
CO0301001
CO0201001
CO0101001



你可能感兴趣的:(C#,ASP.NET)