简体   繁体   中英

How to obtain underlaying elements of each item in foreach loop using c#?

I'm not sure how to exactly ask this question but this is the problem:

I got a list which I filter by SubTypeId(Key = 1 or Key = 2), that looks like this:

在此处输入图像描述

As u can see "Key = 1" has 4 objects within: 0, 1, 2 and 3. All these objects have the same TypeDescription. How can i achieve this element "TypeDescription" once within this for each loop?

Thanks in advance::)

You have a few options here:

  1. Group your elements array by two parameters:
var res = Reports.GroupBy(u => new {u.SubTypeId, u.TypeDescription})
                     .Select(r => new
                      {
                         r.Key, // Key here consists of two elements
                         items = r.Select(i => new
                         {
                             i.DocumentPath,
                             i.Id,
                             i.Name,
                             i.SubTypeDescription,
                             i.TypeId
                         })
                      }).ToList();

In this case, as a result, you will have a collection of SubtypeId and TypeDescription items grouped, containing a collection of all other elements you need.

  1. Create a nested grouping:
var res2 = Reports.GroupBy(u => u.SubTypeId)
                          .Select(r => r.ToList()
                                        .GroupBy(r => r.TypeDescription)
                                        .Select(item=> new {
                                             item.Key,
                                             items = item.Select(i => new 
                                             {
                                                  i.DocumentPath,
                                                  i.Id,
                                                  i.Name,
                                                  i.SubTypeDescription,
                                                  i.TypeId
                                             })
                                         })).ToList();

In this case, you will have a bit more nestings, but the data output will probably be more close to what you were initially requesting.


A few advises:

  1. Please try to avoid array manipulations inside the loop subject, like in the above case, you did array grouping in the foreach collections input section. Instead, assign the array manipulations to a separate variable before the loop.
  2. Instead of anonymous objects, try using real class models.
    Note: in above examples, I've used Anonymous object just for demonstration purposes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM