繁体   English   中英

如何使用此 foreach 循环编写 linqu 查询

[英]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);
    }                                                          
}

它可能看起来像:

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

一种方法是简单地使用WhereConcat

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

如果他们有一个共同的接口,它可以被简化。

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

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

你可以这样做。

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

并且以类似的方式,您可以为循环的 rest 做。

如果可能,您可以尝试:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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