Nick
Nick

Reputation: 6588

Convert Lambda into Linq Statement with nested for loop

Is there a way to rewrite the GetTransformedCollection method below so that it uses a Linq statement and not an expression? I'm currently trying to get around the “A lambda expression with a statement body cannot be converted to an expression tree” error.

public class Obj1
{
    public int Id { get; set; }
    public string[] Names { get; set; }
    public string[] Tags { get; set; }
}

public class EntCollections
{
    private List<Obj1> _results;

    [SetUp]
    public void SetUp()
    {
        _results = new List<Obj1>
        {
            new Obj1 {Id = 1, Names = new[] {"n1"}, Tags = new[] {"abc", "def"}},
            new Obj1 {Id = 2, Names = new[] {"n2", "n3"}, Tags = new[] {"ghi"}},
            new Obj1 {Id = 3, Names = new[] {"n1", "n3"}, Tags = new[] {"def", "xyz"}}
        };
    }

    private static Dictionary<string, List<string>>
        GetTransformedCollection(IEnumerable<Obj1> results)
    {
        var list = new Dictionary<string, List<string>>();

        foreach (var result in results)
        {
            foreach (var id in result.Names)
            {
                if (list.ContainsKey(id))
                {
                    list[id].AddRange(result.Tags);
                }
                else
                {
                    list.Add(id, result.Tags.ToList());
                }
            }
        }

        return list;
    }

    [Test]
    public void Test()
    {
        var list = GetTransformedCollection(_results);

        Assert.That(list["n1"], Is.EquivalentTo(new [] { "abc", "def", "def", "xyz" }));
        Assert.That(list["n2"], Is.EquivalentTo(new [] { "ghi" }));
        Assert.That(list["n3"], Is.EquivalentTo(new [] { "ghi", "def", "xyz" }));
    }

P.s I'm not too worried about the result type being a Dictionary, that was just the simplist way to express it as a return type.

Upvotes: 1

Views: 726

Answers (2)

Ilya Ivanov
Ilya Ivanov

Reputation: 23626

Idea is to find all keys for resulting dictionary and then find corresponding values from original sequence of Obj1

var distinctNames = results.SelectMany(val => val.Names).Distinct();

return distinctNames
      .ToDictionary(name => name, 
                    name => results
                            .Where(res => res.Names.Contains(name))
                            .SelectMany(res => res.Tags)
                            .ToList());

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1499810

I would personally use an ILookup, which is a good bet whenever you have a Dictionary<T1, List<T2>>, and is built with ToLookup():

// Flatten the objects (lazily) to create a sequence of valid name/tag pairs
var pairs = from result in results
            from name in result.Names
            from tag in result.Tags
            select new { name, tag };

// Build a lookup from name to all tags with that name
var lookup = pairs.ToLookup(pair => pair.name, pair => pair.tag);

Upvotes: 7

Related Questions