Linq Query to IEnumerable <T> Extension Method
Consider this,
class Item
{
public string ID { get; set;}
public string Description { get; set; }
}
class SaleItem
{
public string ID { get; set;}
public string Discount { get; set; }
}
var itemsToRemoved = (List<Item>)ViewState["ItemsToRemove"];
// get only rows of ID
var query = from i in itemsToRemoved select i.ID;
var saleItems= (List<SaleItem>)ViewState["SaleItems"];
foreach (string s in query.ToArray())
{
saleItems.RemoveItem(s);
}
How to write this LINQ phrase using IEnumerable / List extension methods
// get only rows of ID
var query = from i in items select i.ID;
early.
+3
3 answers
This is easy:
var query = items.Select(i => i.ID);
SentenceA selectalways matches the challenge select. Some of the other operators have a more complex extension :) If you work a lot, you can force the compiler to do very strange stuff ...
You can find all the details of this and other translations of the query expression in section 7.16 of the C # specification (v3 or v4).
<plug>
You can also buy C # in Depth, 2nd edition and read Chapter 11 if you really wanted to :)</plug>
+5
:
var query = items.Select(i => i.ID);
:
ToArray:
foreach (string s in query.ToArray())
, , List.RemoveAll . , , . RemoveAll, , .
List<Item> itemsToRemove = (List<Item>)ViewState["ItemsToRemove"];
HashSet<string> itemIds = new HashSet<string>(itemsToRemove.Select(s => s.ID));
saleItems.RemoveAll(c => itemIds.Contains(c.ID));
+4