Perhaps breaking down what this expression does will help you understand it:
fruits.Select((fruit, index) =>
new { index, str = fruit.Substring(0, index) });
Select(...) = With the input, return an output as indicated within.
(fruit, index) = Assign the selected fruit to the variable fruit, and the index (position in Enumerable) into index. As mentioned, this is simply one overload (option) available to you. If you don't care about the index value, simply omit it.
=> = return the following value
new { ... } = Create an instance of an anonymous type. This type will have two properties: index, and str. The value of index will be the variable index. the value of str will be the result of the substring on the fruit.
So, if you simply want the fruit, you could rewrite it like so:
fruits.Select(fruit => fruit);
If you still want the index, with the full name of the fruit:
fruits.Select((fruit, index) =>
new { index, str = fruit});
Select is useful for returning a different set of information from what the input was.
By way of example using a slightly more complex scenario:
For instance, if you had classes like so:
public class Customer {
public int Id {get; set;}
public string Name { get; set;}
public List<Order> Orders { get; set;}
}
public class Order {
public int Id { get;set;}
public double TotalOrderValue { get;set}
}
You could use a simple Select statement to return the customer, and the sum of how much that customer has ever ordered:
var customersTotalSpend = customers.Select(
customer =>
new {
customer,
TotalSpend = customer.Orders.Select(order => order.TotalOrderValue).Sum()
});
We could then do something with that TotalSpend value if we wanted, eg getting the 10 biggest spenders:
var biggestCustomers = customersTotalSpend.OrderByDescending(customerSpend=> customer.TotalSpend).Take(10);
Does that make sense now?
foreach (var fruit in fruits)loop and skip the LINQ syntax altogether.foreachiterates from 0 to count, from count to 0 or randomly.for (int index = 0; index < fruits.Count; index++). And loops iterate from 0 to count.