How to concatenate field in list of objects

Viewed 31

I have a list of objects with field String[]. Objects in list >8000 And i need to get String[] with all values from this field from this list

i can do this with loop as below. But can i do this via LINQ (shorter and more efficient) ?

List<ProductInfo> productInfos = new List<ProductInfo>();
ProductInfo f1 = new ProductInfo();
f1.tags = new[] { "A","B","T","U"};
ProductInfo f2 = new ProductInfo();
f2.tags = new[] { "C","D","M","U" };
productInfos.Add(f1);
productInfos.Add(f2);

List<String> res = new List<string>();
productInfos.ForEach(f =>
{
    
    foreach (String tag in f.tags)
    {
        res.Add(tag);   
    }
});
res = res.Distinct().ToList();
class ProductInfo
{
    public String[] tags;
}

But can i do this with LINQ ?

2 Answers

You can use SelectMany for that.

List<String> res = productInfos.SelectMany(x => x.tags)
    .Distinct()
    .ToList();
Related