How to cleverly create an anonymous type from an IEnumerable
本文关键字:an type from IEnumerable anonymous How cleverly create to | 更新日期: 2023-09-27 18:28:39
我想使用LINQ来解决以下问题,我有以下集合:
List<byte> byteList = new List<byte() { 0x01, 0x00, 0x01, 0x02, 0x01, 0x00, 0x3, 0x4, 0x02 };
本例中的数据遵循以下模式:
byteList[0]=地址(1,2,3,…n)
byteList[1]=旧状态,它基本上代表枚举
byteList[2]=新状态,与上述相同
我正在与嵌入式设备接口,这就是我查看输入变化的方式。
为了清理代码,让维护程序员更容易遵循我的逻辑,我想抽象掉一些相关的细节,并将每个三字节的数据集提取到一个匿名类型中,以便在函数中使用,以执行一些额外的处理。我已经编写了一个快速实现,但我相信它可以大大简化。我正在努力清理代码,而不是搅乱局面!必须有一种更简单的方法来完成以下操作:
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);
}
您可以使用Enumerable.Range
和一些数学:
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],
});
如果字节数不是3的倍数,则会忽略额外的一个或两个字节。
为了简化,我会创建一个记录类型并使用for
循环:
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]);
}
或者,如果你确实需要一个匿名类型,你可以在没有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非常有用,但在这个任务中它很尴尬,因为序列项根据它们在序列中的位置而有不同的含义。
我不确定这是否是一个聪明的解决方案,但我使用该示例尝试在不创建单独列表的情况下实现这一点。
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();
如果您必须使用LINQ(不确定它是一个好的计划),那么一个选项是:
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);
}
}
}
这个怎么样?
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]
};
注意:我独立于Michael Liu的答案开发了这个答案,虽然他的答案实际上是一样的,但我将把这个答案留在这里,因为它看起来更漂亮。:-)
这里尝试使用扩展方法ChunkToList
来实现这一点,该方法将IEnumerable<T>
拆分为IList<T>
的块。
用法:
var compObjs = byteList.ChunkToList(3)
.Select(arr => new {
Address = arr[0],
OldValue = arr[1],
NewValue = arr[2]
});
实施:
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;
}
}
}