Reputation: 20004
I have a list:
var _books = new List<int> {233,5,20};
And a ListBox with a lot of books (their value is an item id)
How do I take this working code:
var t = from ListItem n in lbBooks.Items
where _books.Contains(int.Parse(n.Value))
select n;
foreach(ListItem i in t)
{
i.Selected = true;
}
and convert it to lambda:
lbBooks.Items.Cast<ListItem>()
.Where(n => _books.Contains(int.Parse(n.Value)))
.Select(n => n.Selected = true);
Upvotes: 0
Views: 2021
Reputation: 7126
Your not far off, you need to return the whole object and set Selected to true. Something like:
lbBooks.Items.Cast<ListItem>()
.Where(n => _books.Contains(int.Parse(n.Value)))
.Select(n => SetSelected(n));
The above .Select can be shortend to .Select(SetSelected);
if you prefer
private ListItem SetSelected(ListItem listItem)
{
listItem.Selected = true;
return listItem
}
Additionally to save casting you could utilise the SetSelected to handle your casting once you have just the records you want. Your query would then become:
lbBooks.Items.Where(n => _books.Contains(int.Parse(n.Value)))
.Select(n => SetSelected(n));
private ListItem SetSelected(Item item)
{
ListItem result = item as ListItem;
result.Selected = true;
return result;
}
Upvotes: 1
Reputation: 20004
Cast to .ToList()
and use the `ForEach' operator as so:
lbBooks.Items.Cast<ListItem>()
.Where(n => _books.Contains(int.Parse(n.Value)))
.Select(n => n).ToList().ForEach(n=> n.Selected=true);
Upvotes: 0
Reputation: 244757
The best option? Don't. LINQ queries are supposed to be just that – queries. And queries aren't supposed to have side effects. Your approach using foreach
is perfectly fine.
If you really wanted, you could create your own extension method ForEach()
, similar to the one on List<T>
, but I don't think that's a good idea.
Upvotes: 1
Reputation: 46909
There is no build in ForEach extension method. You can create your own, but I do not see any problem with the code you have.
Upvotes: 0