创建一个新的匿名类型列表以合并到现有的匿名类型列表 [英] Create a new anonymous type list to union onto existing anonymous type list

查看:125
本文介绍了创建一个新的匿名类型列表以合并到现有的匿名类型列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从数据库中获得的匿名类型的列表:

I have a list of anonymous types that I get from my database:

var takenChannels = (from b in bq.GetStuff(db)
                     where b.RecordType == "H" && b.TourStartDateTime.Date == date
                     select new { Start = b.TourStartDateTime, End = b.TourEndDateTime, Channel = b.RadioChannel, TourArea = b.TourArea }).ToList();

然后,我使用此列表信息在foreach循环中执行一些操作.我想在循环中返回时为该列表添加一个新的匿名项目.

Then I use this list info to do some stuff in a foreach loop. I want to add to this list a new anonymous item for when I come back round in the loop.

类似的东西:

takenChannels.Union{new[] { new{Start = DateTime.Now, End = DateTime.Now.AddDays(1), Channel = 25, TourArea = "Area" }});

显然这是行不通的.我该怎么办?

Obviously this doesn't work. How do I do it?

takenChannels.Add(new { Start = s, End = e, Channel = channel, TourArea = booking.TourArea });

这是我到目前为止最接近的(感谢Daniel)...但是我得到的错误是:

This is the closest I've got so far (Thanks to Daniel)... but the error I get is:

错误6参数1:无法从"AnonymousType#2"转换为"AnonymousType#1"

Error 6 Argument 1: cannot convert from 'AnonymousType#2' to 'AnonymousType#1'

推荐答案

这个答案可能有点晚了,但是由于这是我在谷歌搜索同一问题时发现的问题,我认为我应该以一个可行的答案来完成它

This answer might be a bit late, but since this is the question I found when Googling for the same problem, I think I should complete it with a working answer.

对于Union,匿名类型多次没有问题.重要的是,必须在所有实例中声明所有属性,并且它们具有相同的数据类型.如果没有,您将得到上面的错误.

There is no problem to Union multiple times over anonymous types. It is important that all properties are declared in all instances and that they have the same data type. if not, you get the error above.

  • 在您的特定情况下,数据库是否可能将TourStartDateTimeTourEndDateTime作为DateTime?返回?
  • RadioChannel是数据库中的int还是int?string?
  • 数据库中的TourAreastring吗?
  • In your specific case, does the database perhaps return TourStartDateTime or TourEndDateTime as DateTime??
  • Is RadioChannel an int from the database or perhaps an int? or string?
  • Is TourArea a string in the database?

只需确保数据类型匹配,就可以了.以下是我在自己的程序中使用的有效代码段:

Just make sure the data types match and you should be fine. Below is a working snippet of code I use in my own program:

var regions = (
    new[] { new { Id = "-1", Name = "---", Pattern = (string)null } }
  ).Union(
    from x in db.Userlists where x.ListType == 2 select new { Id = x.UserlistID.ToString(), Name = x.Name, Pattern = (string)null }
  ).Union(
    from x in db.Lookups where x.Category == "Stock" select new { Id = x.Key, Name = x.Key, Pattern = x.Value }
  ).ToArray();

这篇关于创建一个新的匿名类型列表以合并到现有的匿名类型列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆