I am new in c# and have a problem with lists.
I have a class Message:
public class Message
{
public int MessageId { get; set; }
public DateTime CreatedDate { get; set; }
public string Text { get; set; }
public string Autor { get; set; }
public string Source { get; set; }
}
and class MessageHandler:
class MessageHandler
{
private List<Message> _dummyMessages = new List<Message>()
{
new Message(){
MessageId = 1,
CreatedDate = new DateTime(2014, 5, 27),
Text = "Srpska vodoprivreda...",
Autor = "Marko Markovic",
Source = "Twitter"
},
new Message(){
MessageId = 2,
CreatedDate = new DateTime(2014, 5, 27),
Text = "Aerodrom Beograd...",
Autor = "Zoran Zoric",
Source = "B92"
}
};
public List<Message> GetLatestMessages(int nrMessagesToReturn)
{
List<Message> retVal;
retVal = this._dummyMessages.GetRange(0, nrMessagesToReturn);
return retVal;
}
//todo: Search list _dummyMessages and get Source and
//check is it equal to "Twitter"
}
My problem is that I dont know how to get Source from List<Message>
:( I started like this:
public List<Message> SearchBySource()
{
List<Message> retVal;
foreach (Message m in _dummyMessages)
{
//..........
}
return retVal;
}
but what to do to get Source from Message?
I want to take Source from Message and then check is it "Twitter", because I want to count all "Twitter" sources from my list...
Sorry for stupid question, and thanks for help!!
var count = _dummyMessages.Count(m => m.Source == "Twitter");
ref: http://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b
Try this one:
List<Message> retVal;
foreach (Message m in _dummyMessages)
{
// Check if the message's source is twitter
if(Message.Source=="Twitter")
retVal.Add(Message);
}
return retVal;
Or using LINQ:
return _dummyMessages.Where(x=>x.Source=="Twitter").ToList();
Both of the above code samples will go in the body of SearchBySource()
method.
One suggestion I have to make is you use a parameter, like below:
public List<Message> SearchBySource(string source)
{
return _dummyMessages.Where(x=>x.Source==source).ToList();
}
in order your method being more meaningfull. You are seraching by source, so you have to provide the source.
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