简体   繁体   中英

Distinct() strings from column of string[] array, how to get this with pure LINQ?

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.

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM