Nate
Nate

Reputation: 901

How to cleverly create an anonymous type from an IEnumerable<T>?

I would like to use LINQ to solve the following problem, I have the following collection:

List<byte> byteList = new List<byte() { 0x01, 0x00, 0x01, 0x02, 0x01, 0x00, 0x3, 0x4, 0x02 };

The data in this example follows the following pattern:

byteList[0] = address (1, 2, 3, ... n)

byteList[1] = old state, which is basically representative of an enum

byteList[2] = new state, same as above

I am interfacing with an embedded device and this is how I can view changes in inputs.

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:

List<byte> byteList = new List<byte>()
{
    0x01, 0x09, 0x01, 0x02, 0x08, 0x02, 0x03, 0x07, 0x03
};
var addresses = byteList
    .Where((b, i) => i % 3 == 0)
    .ToList();
var oldValues = byteList
    .Where((b, i) => i % 3 == 1)
    .ToList();
var newValues = byteList
    .Where((b, i) => i % 3 == 2)
    .ToList();

var completeObjects = addresses
    .Select((address, index) => 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);
}

Upvotes: 4

Views: 4353

Answers (6)

markmuetz
markmuetz

Reputation: 9654

Here's an attempt to do it with an extension method ChunkToList that splits up an IEnumerable<T> into chunks of IList<T>'s.

Usage:

        var compObjs = byteList.ChunkToList(3)
                               .Select(arr => new { 
                                       Address  = arr[0],
                                       OldValue = arr[1],
                                       NewValue = arr[2] 
                               });

Implementation:

static class LinqExtensions
{
    public static IEnumerable<IList<T>> ChunkToList<T>(this IEnumerable<T> list, int size)
    {
        Debug.Assert(list.Count() % size == 0);

        int index = 0;
        while (index < list.Count())
        {
            yield return list.Skip(index).Take(size).ToList();
            index += size;
        }
    }
}

Upvotes: 0

StriplingWarrior
StriplingWarrior

Reputation: 156504

How about this?

var addresses = 
    from i in Enumerable.Range(0, byteList.Count / 3)
    let startIndex = i * 3
    select new
    {
        Address = byteList[startIndex],
        OldValue = byteList[startIndex + 1],
        NewValue = byteList[startIndex + 2]
    };

Note: I developed this independently of Michael Liu's answer, and while his is practically the same I'm going to leave this answer here because it looks prettier to me. :-)

Upvotes: 0

Michael Liu
Michael Liu

Reputation: 55369

You can use Enumerable.Range and a little math:

List<byte> byteList = new List<byte>()
{
    0x01, 0x09, 0x01, 0x02, 0x08, 0x02, 0x03, 0x07, 0x03
};
var completeObjects = Enumerable.Range(0, byteList.Count / 3).Select(index =>
    new
    {
        Address = byteList[index * 3],
        OldValue = byteList[index * 3 + 1],
        NewValue = byteList[index * 3 + 2],
    });

If the number of bytes is not a multiple of 3, the extra one or two bytes will be ignored.

Upvotes: 5

phoog
phoog

Reputation: 43046

For simplification, I'd create a record type and use a for loop:

class RecordType
{
    //constructor to set the properties omitted
    public byte Address { get; private set; }
    public byte OldValue { get; private set; }
    public byte NewValue { get; private set; }
}

IEnumerable<RecordType> Transform(List<byte> bytes)
{
    //validation that bytes.Count is divisible by 3 omitted

    for (int index = 0; index < bytes.Count; index += 3)
        yield return new RecordType(bytes[index], bytes[index + 1], bytes[index + 2]);
}

Alternatively, if you definitely need an anonymous type, you can do that without linq:

for (int index = 0; index < bytes.Count; index += 3)
{
    var anon = new { Address = bytes[index], OldValue = bytes[index + 1], NewValue = bytes[index + 3] };
    //... do something with anon
}

Linq is very useful, but it's awkward at this task, because the sequence items have a different meaning depending on their location in the sequence.

Upvotes: 3

Stuart Golodetz
Stuart Golodetz

Reputation: 20616

If you must use LINQ (not sure it's a good plan), then one option is:

using System;
using System.Collections.Generic;
using System.Linq;

static class LinqExtensions
{
    public static IEnumerable<T> EveryNth<T>(this IEnumerable<T> e, int start, int n)
    {
        int index = 0;
        foreach(T t in e)
        {
            if((index - start) % n == 0)
            {
                yield return t;
            }
            ++index;
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        List<byte> byteList = new List<byte>()
        {
            0x01, 0x09, 0x01, 0x02, 0x08, 0x02, 0x03, 0x07, 0x03
        };

        var completeObjects =
            byteList.EveryNth(0, 3).Zip
            (
                byteList.EveryNth(1, 3).Zip
                (
                    byteList.EveryNth(2, 3),
                    Tuple.Create
                ),
                (f,t) => new { Address = f, OldValue = t.Item1, NewValue = t.Item2 }
            );

        foreach (var anonType in completeObjects)
        {
            Console.WriteLine("Address: {0}\nOld Value: {1}\nNew Value: {2}\n", anonType.Address, anonType.OldValue, anonType.NewValue);
        }
    }
}

Upvotes: 0

sisve
sisve

Reputation: 19781

I'm not sure this qualifies as a clever solution, but I used the example to try to accomplish this without creating separate lists.

var completeObjects = byteList
    // This is required to access the index, and use integer
    // division (to ignore any reminders) to group them into
    // sets by three bytes in each.
    .Select((value, idx) => new { group = idx / 3, value })
    .GroupBy(x => x.group, x => x.value)

    // This is just to be able to access them using indices.
    .Select(x => x.ToArray())

    // This is a superfluous comment.
    .Select(x => new {
        Address = x[0],
        OldValue = x[1],
        NewValue = x[2]
    })

    .ToList();

Upvotes: 0

Related Questions