0
我有一個IEnumerable<byte>
我想要轉換爲new object { byte property1, byte property2, ....}
,將所有這些字節值加入到一個對象中。LINQ:如何將IEnumerable <SomeType>加入具有SomeType屬性的對象中?
我如何使用LINQ?
我有一個IEnumerable<byte>
我想要轉換爲new object { byte property1, byte property2, ....}
,將所有這些字節值加入到一個對象中。LINQ:如何將IEnumerable <SomeType>加入具有SomeType屬性的對象中?
我如何使用LINQ?
我不知道爲什麼你想達到那個,但我認爲有一種方法,從System.Dynamics
使用ExpandoObject
。
它可以通過Aggregate
方法來完成從LINQ:
return source.Select((x, i) => new {name = string.Format("{0}{1}", propertyPrefix, i), value = x})
.Aggregate((new ExpandoObject()) as IDictionary<string, Object>,
(e, i) =>
{
e[i.name] = i.value;
return e;
}, e => e as ExpandoObject);
你應該把它隱藏在另一種擴展方法,像ToExpandoObject
:
public static ExpandoObject ToExpandoObject<TSource>(this IEnumerable<TSource> source, string propertyPrefix)
{
return source.Select((x, i) => new {name = string.Format("{0}{1}", propertyPrefix, i), value = x})
.Aggregate((new ExpandoObject()) as IDictionary<string, Object>,
(e, i) =>
{
e[i.name] = i.value;
return e;
}, e => e as ExpandoObject);
}
用法:
var source = new List<int>() {123, 234, 345, 456, 567, 678};
var t = source.ToExpandoObject("Property");
他們已經在一個對象中。調用'.ToArray()'然後你可以索引值。 – Jay 2013-04-24 14:19:55
爲什麼要創建一個匿名類型,其中包含您的字節列表中的所有屬性?即使僅存儲完整集合,也可以通過索引器訪問每個字節。 – 2013-04-24 14:20:25
b/c我做了一個對象的集合,只選擇字節類型的屬性,如下所示:IEnumerable tacticbyte = tactic.GetType()。GetProperties()。其中(p => p.GetValue(策略)是字節)。選擇(p =>(byte)p.GetValue(tactic)); 所以我想在新的類型中一起使用這些字節屬性 –
2013-04-24 14:30:21