简体   繁体   中英

How to write a linqu query with this foreach loop

This below is my code and I want to write a linq query for this three list (Dictionaryfilter,collectionfilter,reffrencefilter) this as are mmy list and want to add when item is selected then add into a SelectedIdList,Using Linq in c#

SelectedIdList = new List<long>();
foreach (var item in DictionariesFilter)
{
    if (item.IsSelected)
    {
        SelectedIdList.Add(item.DictionaryId);
    }
}

foreach (var item in CollectionsFilter)
{
    if (item.IsSelected)
    {
        SelectedIdList.Add(item.DictionaryId);
    }
}

foreach (var item in RefrencesFilter)
{
    if (item.IsSelected)
    {
        SelectedIdList.Add(item.DictionaryId);
    }                                                          
}

It could look something like:

SelectedIdList.AddRange(
    DictionariesFilter.Where(x=>x.IsSelected).Select(x=>(long)x.DictionaryId)
);
SelectedIdList.AddRange(
    CollectionsFilter.Where(x=>x.IsSelected).Select(x=>(long)x.DictionaryId)
);
SelectedIdList.AddRange(
    RefrencesFilter.Where(x=>x.IsSelected).Select(x=>(long)x.DictionaryId)
);

One way of doing this is to simply use Where and Concat .

SelectedIdList = DictionariesFilter.Where(x => x.IsSelected).Select(x => (long)x.DictionaryId)
    .Concat(CollectionsFilter.Where(x => x.IsSelected).Select(x => (long)x.DictionaryId))
    .Concat(RefrencesFilter.Where(x => x.IsSelected).Select(x => (long)x.DictionaryId))
    .ToList();

If they have a common interface it could be simplified.

public interface IFilter
{
    bool IsSelected { get; }
    long DictionaryId { get; }
}

SelectedIdList = DictionariesFilter
    .Concat(CollectionsFilter)
    .Concat(RefrencesFilter)
    .Where(x => x.IsSelected)
    .Select(x => x.DictionaryId)
    .ToList();

You can do like this.

var results1 = from item in DictionariesFilter
                              where item.IsSelected
                              select item.DictionaryId;
     selectedList.Add(results1);

and in similar way you could do for the rest of loops.

You could try, if possible:

public interface IFilter
{
    bool IsSelected { get; }
    int DictionaryId { get; }
}

SelectedIdList = new IFilter[] { DictionariesFilter, CollectionsFilter, ReferencesFilter}
    .SelectMany(dic => dic.Where(x => x.IsSelected).Select(x = > (long)x.DictionaryId) )
    .ToList();

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