Vivendi
Vivendi

Reputation: 21097

Join a string property which is in a List of objects using Linq

I have a set of object like this:

class ObjectA
{
    public string NameA {get;set;}
    public List<ObjectB> ListObjectB {get;set;}
}

class ObjectB
{
    public string NameB {get;set;}
    public ObjectBDetails Details {get;set;}
}

class ObjectBDetails 
{
    public string Code {get;set;}
    public string Sector {get;set;}
}

I have a List of ObjectA with a few items in there.

What I like to do is get the Sector string of all the items and write that out as a comma separated string.

So for example, I could do something like this:

string tmp = "";
foreach(var objA in ListObjectA)
{
    foreach(var objB in objA.ListObjectB)
    {
        tmp += objB.ObjectDetails.Sector + ", ";
    }
}

This "Would" work. Only problem is that it will always end with a ,, which is not so nice.

But I also think that there is a much nicer solution to do this with Linq. But I can't figure out how to do it. I tried something like this, but obviously it didn't work out:

var a = objA.ListObjectB.Aggregate((current, next) => current.ObjectBDetails.Sector + ", " + next.ObjectBDetails.Sector);

So I'm actually looking for a way to do this with Linq. Anyone any idea how to do this?

Upvotes: 1

Views: 606

Answers (2)

Konrad Kokosa
Konrad Kokosa

Reputation: 16898

You can use string.Join and LINQ SelectMany combination:

var a  = string.Join(", ", ListObjectA.SelectMany(x => x.ListObjectB)
                                      .Select(x => x.Details.Sector));

This for data:

var ListObjectA = new List<ObjectA>();
ListObjectA.Add(new ObjectA()
{
    ListObjectB = new List<ObjectB>() { 
        new ObjectB() { Details = new ObjectBDetails() { Sector = "A1" }},
        new ObjectB() { Details = new ObjectBDetails() { Sector = "A2" }},
    }
});
ListObjectA.Add(new ObjectA()
{
    ListObjectB = new List<ObjectB>() { 
        new ObjectB() { Details = new ObjectBDetails() { Sector = "B1" }}
    }
});

produces "A1, A2, B1"

Upvotes: 4

Toothbrush
Toothbrush

Reputation: 2141

Try this:

var a = objA.ListObjectB.Aggregate((current, next) => current.Sector + ", " + next.Sector);

Upvotes: -1

Related Questions