Reputation:
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);
}
}
Upvotes: 0
Views: 81
Reputation: 3250
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();
Upvotes: 0
Reputation: 2965
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();
Upvotes: 0
Reputation: 74605
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)
);
Upvotes: 1
Reputation: 13
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.
Upvotes: 0