简体   繁体   中英

Mapping List<List<Object>> to a Dictionary with maximum value of object properties

I have a List<List<PersonTypeAccess>> . PersonTypeAccess is an object that has 2 properties: PersonType and AccessType . These are both an enum.

If I try visualizing it, the lists could possibly look like this:

{
{ PersonType = 0, AccessType = 2},
{ PersonType = 5, AccessType = 0},
{ PersonType = 2, AccessType = 1}
},
{
{ PersonType = 6, AccessType = 1},
{ PersonType = 3, AccessType = 0}
},
{
{ PersonType = 3, AccessType = 1},
{ PersonType = 5, AccessType = 0},
{ PersonType = 8, AccessType = -1},
{ PersonType = 0, AccessType = 1}
}

I need to create a Dictionary<PersonType, AccessType> that only has each PersonType once, combined with its highest AccessType value found troughout the lists.

For my example above that would be:

{
PersonType 0 -> AccessType 2,
PersonType 8 -> AccessType -1,
PersonType 5 -> AccessType 0,
PersonType 3 -> AccessType 1,
PersonType 6 -> AccessType 1,
PersonType 2 -> AccessType 1
}

How would I go about doing this?

You can use SelectMany to flatten the lists. You then use GroupBy to group by PersonType , where in the result selector you use Max on the individual elements ( AccessType cast to int ) and select an anonymous type containing each PersonType and it's maximum AccessType . Finally you project that to a dictionary using ToDictionary .

var dict = list
     .SelectMany(c => c)
     .GroupBy(
        c => c.PersonType, 
        c => (int) c.AccessType,
        (key, els) => new { 
           PersonType = key, 
           AccessType = (AccessType)els.Max()
        })
     .ToDictionary(c => c.PersonType, c => c.AcessType);

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