None
None

Reputation: 5670

Fetch months inside list using Linq

I have list like this

 public class Result
{
    public string id { get; set; }
    public string name { get; set; }
    public string startDate { get; set; } //smaple date 2014-03-31T12:30:03
}


List<Result>

Now I want to get all month names that's inside startDate of this list.And I tried some thing like this

List<string> mnamesList= result.Select(s => Convert.ToDateTime(s.startDate).ToString("MMMM")).ToList();

As you can see this loop will return repeated month names, I don't know how to fetch only different moths using Linq. Can any one point out the correct way?

Upvotes: 0

Views: 103

Answers (3)

Christos
Christos

Reputation: 53958

Try this one:

List<string> months = result.Select(s => DateTime.Parse(s.StartDate))
                            .Select(x=>x.ToString("MMMM"))
                            .Distinct()
                            .ToList();

Upvotes: 1

Stefan Koenen
Stefan Koenen

Reputation: 2337

I think you can use the Linq Distinct() function as follows:

List<string> mnamesList= result.Select(s => Convert.ToDateTime(s.startDate).ToString("MMMM")).Distinct().ToList();

Upvotes: 1

Raja Nadar
Raja Nadar

Reputation: 9499

you're looking for the Distinct method.

List<string> distinctMonths = result.Select(s => 
  Convert.ToDateTime(s.startDate).ToString("MMMM")).Distinct().ToList();

Upvotes: 1

Related Questions