Reputation: 81
i want to add this line to my list but when i put this message error results.Add("TOUT");
how can i add TOUT to the list
this is the method in when i want to add a new element
dynamic results = (from ta in db.client
select new
{
Name= ta.Name
}).Distinct().ToList();
Can someone help me to fix this and thank you for your help
Upvotes: 0
Views: 70
Reputation: 37000
Linq is not created to support data-manipulation but data-query. Thus you have to turn your results in any kind of list where you CAN add elements. e.g:
var results = (from ta in db.client
select new
{
Name= ta.Name
}).Distinct().ToList();
Now you can simply add your element by creating an anonymous instance sharing the properties you need.
results.Add(new { Name = "TOUT" });
Notice that the keyword dynamic
is not needed here as the returned list is already strongly-typed (although there is no class-definition within your assembly for it, the definition resides within a temporary assembly where the type is called anonymous
).
EDIT: To simplify things you can also ommit the anonymous type completely and select only the name
.
So instead of
select new { ... }
you write
select ta.Name
Thus you get a list of strings where you can simply add your last element TOUT
.
Upvotes: 1
Reputation: 8894
You cannot add a string
to the list because you are not creating a list of strings. You are creating a list of instances of an anonymous type.
There is almost never a need to create an anonymous type with only one property, so just select the string:
(from ta in db.client select ta.Name).Distinct().ToList()
or just
db.client.Select(ta => ta.Name).Distinct().ToList()
This will create a List<string>
. (Assuming ta.Name is a string
)
Upvotes: 1