我有一个匿名类型列表List<'a>, a' is new {OptionSetValue servingTime, OptionSetValue servingGroup, string servingClass, string desc, string childName, Guid childId, EntityReference item, OptionSetValue type, Guid sensitivity}
我已经在foreach语句中构造了一个这样的列表,并且需要将该列表从for循环(groupedAllergies)外部添加到另一个相同类型的列表中。显然,我写的内容不起作用,因为对象不包含我要访问的匿名类型的定义。我该如何补救?!
var groupedAllergies = new List<object>(); <--- problem
foreach (var line in items)
{
OptionSetValue servingTime = line.servingTime;
OptionSetValue servingGroup = line.servingGroup;
string servingClass = line.servingClass;
string desc = line.desc;
string childName = line.childName;
Guid childId = line.childId;
Guid sensitivity = line.sensitivity;
var queryAllergyItems = groupAllergies.Where(e => e.servingClass == servingClass
&& e.servingTime == servingTime
&& e.servingGroup == servingGroup
&& e.desc == desc
&& e.allergies.Intersect(allergies).Any()).Select(r => new
{
r.item,
r.type,
r.allergies
}).ToList();
var items = queryAllergyItems.Select(r => new
{
servingTime,
servingGroup,
servingClass,
desc,
childName,
childId,
r.item,
r.type,
sensitivity = r.allergies.Intersect(allergies).First()
}).ToList();
items.ForEach(e => groupedAllergies.Add(e));
}
foreach(var allergy in groupedAllergies)
{
var servingTime = allergy.servingTime;
//object doesn't have definition for servingTime!!
}
这是有效的解决方案吗?!
var o = new { servingTime = new OptionSetValue(), servingGroup = new OptionSetValue(), servingClass = "", desc = "", childName = "", childId = new Guid(), item = new EntityReference(), type = new OptionSetValue(), sensitivity = new Guid() };
var groupedAllergies = new[] { o }.ToList();
groupedAllergies.Clear();
答案 0 :(得分:0)
尝试一下:
List<dynamic> list = new List<dynamic>();
这将创建一个可以存储任何类型对象的列表。
答案 1 :(得分:0)
如果您使用的是C#7,则实际上不需要匿名类型。您可以使用值元组。它们基本上是具有特殊语言支持的元组。
https://blogs.msdn.microsoft.com/mazhou/2017/05/26/c-7-series-part-1-value-tuples/
对于List<dynamic>
,取决于类型是否相同,动态性会变得非常快。不会比静态类型快。