How to rewrite given foreach loop using LINQ where statemetn?
List<ItemData> dbItems = _dataService.GetAllItems();
List<ItemModel> modeList = new List<ItemModel>();
foreach (ItemData p in dbItems )
{
ItemModel m = Mapper.ItemDataToModelMap(p);
modeList.Add(m);
}
I have tried this, but this gives error: Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'System.Collections.Generic.IEnumerable'...
var modeList= from m in dbItems
select new {item = Mapper.ItemDataToModelMap(m)
};
Edit: The method that uses this should return IEnumerable, so this is the error cause. I should not change return type, instaed the code and anonymous type.
To have a List<ItemModel>
as a result try this:
var modeList = dbItems
.Select(m => Mapper.ItemDatatoModelMap(m))
.ToList();
Using query notation:
var modeList = (from m in dbItems select Mapper.ItemDataToModelMap(m))
.ToList();
new { ... }
notation creates an anonymous type , while you need a List<T>
with a particular type - ItemModel
.
Also note, that there is nothing wrong syntactically with:
var modeList= from m in dbItems
select new {item = Mapper.ItemDataToModelMap(m)};
But your description of the error is not clear. You're either not using var
as you've presented (but List<ItemModel>
), or doing something else with modeList
that leads to a type mismatch.
Bit pre coffee here, but is this what you are looking for:
var modeList= from m in dbItems
select Mapper.ItemDataToModelMap(m);
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.