結果をLambdaまたはLinq構文でGroup byして出力する

1888 ワード

        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

出力結果:
CO1001001CO0901001CO0801001CO0701001CO0601001CO0501001CO0401001CO0301001CO0201001CO0101001