score:6
the first block of code builds the items once and returns a list with the items.
the second block of code builds those items each time the ienumerable is walked through.
this means that the second and third line of the first block operate on the same object instance. the second block's second and third line operate on different instances of foo (new instances are created as you iterate through).
the best way to see this would be to set breakpoints in the methods and run this code under the debugger. the first version will only hit the breakpoint once. the second version will hit it twice, once during the .where() call, and once during the .elementat call. (edit: with the modified code, it will also hit the breakpoint a third time, during the tolist() call.)
the thing to remember here is that an iterator method (ie. it uses yield return) will be run every time the enumerator is iterated through, not just when the initial return value is constructed.
score:0
suggestion: compile the code and open with reflector. yield is a syntactical suger. you would be able to see the code logic difference in the code your wrote and the code generated for the yield keyword. both are not the same.
score:1
listtwo is an iterator - a state machine.
elementat must start at the beginning of the iterator to correctly get the i-th index in the ienumerable (whether or not it is an iterator state machine or a true ienumerable instance), and as such, listtwo will be reinitialized with the default values of enabled = true for all three items.
score:2
those are definitely not the same thing.
the first builds and returns a list the moment you call it, and you can cast it back to list and list-y things with it if you want, including add or remove items, and once you've put the results in a variable you're acting on that single set of results. calling the function would produce another set of results, but re-using the result of a single call acts on the same objects.
the second builds an ienumerable. you can enumerate it, but you can't treat it as a list without first calling .tolist()
on it. in fact, calling the method doesn't do anything until you actually iterate over it. consider:
var foolist = data.list2().where(f => f.id > 1);
// no foo objects have been created yet.
foreach (var foo in foolist)
{
// a new foo object is created, but not until it's actually used here
console.writeline(foo.enabled.tostring());
}
note that the code above will create the first (unused) foo instance, but not until entering the foreach loop. so the items aren't actually created until called for. but that means every time you call for them, you're building a new set of items.
Source: stackoverflow.com
Related Query
- Why does LINQ treat two methods that do the "same" thing differently?
- Why the same LINQ expression behaves differently in two different foreach loops?
- Why the default that i see in SQL Server for the fields does no reflected in LINQ
- Why does Linq join on Nullable<T> not work the same as ==?
- Why does LINQ generated SQL include multiple "IS NULL" conditions for the same column
- Linq Group By On Two Properties That maybe different or the same
- Check a list of DTOs using linq to see if all values that exclude a particular value all equal the same thing
- When running a method that uses linq to get the palindromes from a string, why does SelectMany order the resulting strings?
- Linq - Merging two statements that use the same method
- Why does the C# compiler go mad on this nested LINQ query?
- Why LINQ to Entities does not recognize the method 'System.String ToString()?
- Why does the Linq Cast<> helper not work with the implicit cast operator?
- Check that all items of IEnumerable<T?> has the same value using LINQ
- Why don't the Linq extension methods sit on IEnumerator rather than IEnumerable?
- Why the order of LINQ to objects methods counts
- Why does a GC after a LINQ query free the WhereListIterator but not the Func representing the condition?
- Does this LINQ code perform multiple lookups on the original data?
- Why does the Linq OrderBy extension not affect the list it is called on?
- LINQ OrderBy. Does it always return the same ordered list?
- Why does an IF Statement effect the outcome of my LINQ Statement?
- How does linq actually execute the code to retrieve data from the data source?
- How does this linq code that splits a sequence work?
- LINQ Union between two tables with the same fields and then returned in a collection
- Why does Linq do joins differently
- Refactor Linq code and "LINQ to Entities does not recognize the method"
- why does LINQ use the wrong datatype in my query while it's declared correctly in the EF schema?
- Return two types that derive from the same abstract class
- Using LINQ to create pairs from two different list where the entries have same attribute
- Why is IQueryable lacking all the extension methods that IQueryable<T> has?
- How to code the partial extensions that Linq to SQL autogenerates?
More Query from same tag
- Faster alternatives to .Distinct()
- Filter out null values in Linq
- Create a LINQ query comparing arrays
- Retrieve data from many to many relationship in asp.net mvc linq
- Returning Linq query results into a List object (based on condition)
- how to process "parallel" sequences in Linq?
- linq find in which position is my object in List
- How to get the Role's Names for each user in a list?
- LINQ Query with GROUP and SUM
- Get values from json with linq
- C# Linq DeleteObject
- Entity Framework 6: Trim does not work properly
- Linq query to select the records based on the given months for a year
- Unable to filter on Date fields in MongoDB using C# Driver
- Datacontext Object Type for LINQ results
- LINQ group by question
- Is Linq "Where" more expensive than Linq "Select"?
- The repository pattern and LinqToSql methods
- how to speed up query binary search in LINQ
- Grouping hierarchical data with LINQ
- Getting DataGrid current item into an object WPF
- XElement - not able to capture the next node
- Is a Person an aggregate root?
- Loop Through LINQ Query Columns (Not rows)
- How to combine 2 child elements with identical name into single property using XmlSerializer class objects is C#
- Performance comparison Sql query and Linq data query
- How do I modify a collection after being calculated?
- Unable to create a constant value of type 'LookupObject'. Only primitive types or enumeration types are supported in this context
- How to order obj based on their hierachy?
- What is the best way to combine multiple DbQuery results?