开发者

GroupBy without LINQ

I am trying to achieve the following without LINQ:

I have a list of CenterDetail objects (with CenterID and AreaID as property):

  • objCenterDetail1 (CenterID=1, AreaID=1)
  • objCenterDetail2 (CenterID=2, AreaID=1)
  • objCenterDetail3 (CenterID=3, AreaID=1)
  • objCenterDetail4 (CenterID=5, AreaID=2)
  • objCenterDetail5 (CenterID=6, AreaID=2)

I want to create an AreasDictionary as follows:

  • AreaID=1: objCenterDetail1, objCenterDeta开发者_Go百科il2, objCenterDetail3
  • AreaID=2: objCenterDetail4, objCenterDetail5

What is the best solution for this in C# with .NET 2.0?


You probably want something like this:

Dictionary<int, List<CenterDetail>> map = new Dictionary<int, List<CenterDetail>>();
foreach (CenterDetail detail in details)
{
    List<CenterDetail> list;
    if (!map.TryGetValue(detail.AreaID, out list)
    {
        list = new List<CenterDetail>();
        map.Add(detail.AreaID, list);
    }
    list.Add(detail);
}
return map;


Not using LINQ typically means using foreach to iterate over your collection instead:

IEnumerable<Center> centers = // Assume this is your collection;
Dictionary<Area,List<Center>> areasDictionary = new Dictionary<Area,List<Center>>();
foreach(Center center in centers) 
{
    if (!areasDictionary.ContainsKey(center.Area) ) 
        areasDictionary.Add(center.Area, new List<Center>());
    areasDictionary[center.Area].Add(center);
}

Now this probably won't compile in your solution since you haven't given us enough information about the particular types involved, but it does demonstrate the general idea.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜