Search code examples
c#entity-frameworklinq-to-entities

LINQ to Entities - get all related entity field into a string


I have a Person Entity something like that

PersonId
PersonName
PersonPhone

I have a House Entity

HouseID
HouseType
HouseSize

Both Entities are related with many to many relation. I need to have all the HouseType for a person (which has many houses) into a string.


Solution

  • You can easily concatenate multiple strings from a sequence with the Enumerable.Aggregate method.

    In your case you'll have to first project the list of House entities into a list of House.HouseType strings and then aggregate them into a single string:

    var houseTypes = person.Houses.Select(i => i.HouseType).AsEnumerable();
    var emptyResult = "0";
    
    return houseTypes.Any() ?
        houseTypes.Select(i => i.ToString())
                  .Aggregate((current, next) => current + ", " + next) :
        emptyResult;
    

    Alternatively you could simply say:

    var houseTypes = person.Houses
                           .Select(i => i.HouseType)
                           .AsEnumerable()
                           .Select(i => i.ToString());
    return String.Join(", ", houseTypes);
    

    which will return an empty string when the houseTypes sequence is empty.

    Update:

    If you're using Entity Framework 4 or above, you can use one of the built-in SQL functions to perform the conversion to string directly in the database:

    var houseTypes = person.Houses
                           .Select(i => SqlFunctions.StringConvert((double)i.HouseType))
                           .AsEnumerable()
    return String.Join(", ", houseTypes);