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();
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.
Something like:
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?
Edit 1:
takenChannels.Add(new { Start = s, End = e, Channel = channel, TourArea = booking.TourArea });
This is the closest I've got so far (Thanks to Daniel)... but the error I get is:
Error 6 Argument 1: cannot convert from 'AnonymousType#2' to 'AnonymousType#1'
You are not allowed to create a field, property, event, or return type of a method is of anonymous type. You are not allowed to declare formal parameters of a method, property, constructor, indexer as a anonymous type. The scope of the anonymous type is always limited to the method in which they are defined.
You could do: var list = new[] { o, o1 }. ToList();
The compiler generates a name for each anonymous type. If two or more anonymous type objects are defined in the same assembly and the sequence of properties are same in terms of names and types than the compiler treats both as same object instances of type.
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.
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.
TourStartDateTime
or TourEndDateTime
as DateTime?
? RadioChannel
an int
from the database or perhaps an int?
or string
?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();
You can simply Add
to the list:
takenChannels.Add(new { Start = ... });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With