Greg
Greg

Reputation: 11480

Anonymous Type, and the great unknown

I'm attempting to explicitly define Anonymous Type content, but every time I attempt to access the data I receive an error: Does not contain a definition or extension method for argument. Can someone explain to me, why?

params string[] content;
var log = content.Select(obj => new {
     Date = obj.Contains("Date"),
     Title = obj.Contains("Title"),
     Priority = obj.Contains("Priority"),
     Message = obj.Contains("Message")
});

Now if I attempt to to call log.Date that particular message would appear, why? How would I correctly do that?

Upvotes: 0

Views: 67

Answers (4)

Knowledge Lover
Knowledge Lover

Reputation: 31

Select clause returns IEnumerable so if you are sure that the selection of content object will return only one element, you can use SingleOrDefault() function as follow:

var log = content.Select(obj => new {
     Date = obj.Contains("Date"),
     Title = obj.Contains("Title"),
     Priority = obj.Contains("Priority"),
     Message = obj.Contains("Message")
}).SingleOrDefault();

Upvotes: 0

har07
har07

Reputation: 89295

log is IEnumerable of anonymous type in this case. So log it self doesn't have Date member, but item in log has :

var dateOfFirstItem = log.First().Date;

You can do something like this if you're sure there is always at least one item in content :

var log = content.Select(obj => new {
     Date = obj.Contains("Date"),
     Title = obj.Contains("Title"),
     Priority = obj.Contains("Priority"),
     Message = obj.Contains("Message")
}).First();
var date = log.Date
var title = log.Title
....

Upvotes: 3

bit
bit

Reputation: 4487

That is because log is an IEnumerable here. Try this instead

var logs = content.Select(obj => new {
     Date = obj.Contains("Date"),
     Title = obj.Contains("Title"),
     Priority = obj.Contains("Priority"),
     Message = obj.Contains("Message")
});

foreach (var log in logs)
{
    log.Date;
}

To avoid foreach implies you only need one specific item out of the IEnumerable, if it is the first item that you need you can use First() extension.

logs.First();

Otherwise, you may use in usual index like you would do for an array

Upvotes: 4

Loathing
Loathing

Reputation: 5266

Log is an enumerable:

foreach (var o in log) {
    bool date = o.Date;
}

Upvotes: 3

Related Questions