0

I could not find any similar example. In my DB I have a column of string[] array, where they are divided with comma. Example of 3 rows:

id1: apple, orange, banana, kiwi
id2: orange, kiwi
id3: lemon, pineaple, kiwi

From this list I need to extract with LINQ a List of distinct strings: apple, orange, banana, kiwi, lemon, pineapple.

I managed to do it, but not purely LINQ, but when using also foreach:

public async Task<List<string>> GetFruitDetailedType()
        {
            List<string> all = new List<string>();
            var qry = await GetFruitsQueryable().Select(v => v.DetailedType).ToListAsync();
            foreach (var item in qry)
            {
                foreach(var type in item)
                {
                    all.Add(type);
                }
            }
            return (from w in all select w).Distinct().ToList();
        }

Is there a way to do it just with LINQ, without calling for object with all entities?

NOTE: using EF Core 2.

2
  • You're looking for SelectMany to flat map a list of lists. Commented Jan 23, 2020 at 18:04
  • @JonathonChase looks like you are right. Thank you. Is it more efficient than my approach? Do you have any idea maybe? Commented Jan 23, 2020 at 18:10

1 Answer 1

2

Removing the nested for loops is pretty straight-forward, as you're simply doing a flat mapping of a collection of collections. The LINQ extension you want for this is SelectMany. Using it, you could reduce your function to something like this:

public async Task<List<string>> GetFruitDetailedType() 
{
    var qry = await GetFruitsQueryable().Select(v => v.DetailedType).ToListAsync();
    return qry.SelectMany(x => x).Distinct().ToList();
}

I haven't tested the following, but I also suspect it may work as well:

public async Task<List<string>> GetFruitDetailedType()
{
    return await GetFruitsQueryable().SelectMany(x => x.DetailedType)
                                     .Distinct()
                                     .ToListAsync();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.