简体   繁体   中英

Group by a list objects by a dynamically properties values c#

I need to group by a list objects by a dynamically properties values.

My objects are:

public class Person
{
    public string Name {get;set;}
    public List<Contact> Contacts {get;set;}
}

public class Contact
{
    public string Type {get;set;}
    public string Value {get;set;}
}

And I need to group by a Type of Contact (for example: "Site", "Address")

I try to create a lambda expression to represent the search for the type of contact to use in a groupBy clause (selector is my lambda expression):

persons.GroupBy(selector).Select(
    g => new GroupResult<TElement>
    {
        Key = g.Key,
        Items = g,
        SubGroups = g.GroupByMany(nextSelectors)
    });

But i can't create this lambda expression. I obtain an error in a second line:

The 'Type' instance property is not set to type 'ConsoleApplication1.Person'.

How can i represent in a persons list, the "site" contact type ?

var parameterExp = Expression.Parameter(typeof(TElement), "Contacts");
var propertyExp = Expression.Property(parameterExp, "Type");
MethodInfo method = typeof(string).GetMethod("Contains", new[] { typeof(string) });
var someValue = Expression.Constant("Site", typeof(string));
var containsMethodExp = Expression.Call(propertyExp, method, someValue);

Expression<Func<TElement, object>> predicate = Expression.Lambda<Func<TElement, object>>
 (containsMethodExp, parameterExp);

Anyone can help me?

You don't need to create the expression yourself. One way to solve it is to split what you are trying to do in two:

  1. Get all contact types.
  2. Create a dictionary based on each contact type with all the persons that has any contact listed under that type.

This can be done with the following code:

var contactTypes = persons.SelectMany(p => p.Contacts.Select(c => c.Type)).GroupBy(c => c).ToDictionary(c => c.Key);
var groupedPersons = contactTypes.ToDictionary(t => t.Key, t => persons.Where(p => p.Contacts.Any(c => c.Type == t.Key)).ToList());

groupedPersons is a dictionary containing as key the contact type and as values a list of the persons under that contact type.

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