Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to cleverly create an anonymous type from an IEnumerable<T>?
    text
    copied!<p>I would like to use LINQ to solve the following problem, I have the following collection:</p> <pre><code>List&lt;byte&gt; byteList = new List&lt;byte() { 0x01, 0x00, 0x01, 0x02, 0x01, 0x00, 0x3, 0x4, 0x02 }; </code></pre> <p>The data in this example follows the following pattern:</p> <p>byteList[0] = address (1, 2, 3, ... n) </p> <p>byteList[1] = old state, which is basically representative of an enum </p> <p>byteList[2] = new state, same as above</p> <p>I am interfacing with an embedded device and this is how I can view changes in inputs.</p> <p>In order to clean up code and make it easier for a maintenance programmer to follow my logic, I'd like to abstract away some of the nuts and bolts involved and extract each three-byte set of data into an anonymous type to be used within the function to perform some additional processing. I've written a quick implementation, but I'm sure it can be greatly simplified. I'm trying to clean up the code, not muddy the waters! There has to be a simpler way to do the following:</p> <pre><code>List&lt;byte&gt; byteList = new List&lt;byte&gt;() { 0x01, 0x09, 0x01, 0x02, 0x08, 0x02, 0x03, 0x07, 0x03 }; var addresses = byteList .Where((b, i) =&gt; i % 3 == 0) .ToList(); var oldValues = byteList .Where((b, i) =&gt; i % 3 == 1) .ToList(); var newValues = byteList .Where((b, i) =&gt; i % 3 == 2) .ToList(); var completeObjects = addresses .Select((address, index) =&gt; new { Address = address, OldValue = oldValues[index], NewValue = newValues[index] }) .ToList(); foreach (var anonType in completeObjects) { Console.WriteLine("Address: {0}\nOld Value: {1}\nNew Value: {2}\n", anonType.Address, anonType.OldValue, anonType.NewValue); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload