IRFAN SHAIKH
IRFAN SHAIKH

Reputation: 1

How can I use Distinct operator in C# LINQ query

I would like to select unique EventYear using following code in c# Its giving duplicate values. my table (EventMasters) structure is (EventYear (string), EventCode, EventDescription) I want to select unique or distinct EventYear

    public ActionResult EventYearsMenu()
    {
        var eventyears = storeDB.EventMasters.Distinct().ToList().OrderByDescending(c => c.EventYear== c.EventYear.Distinct());
        return PartialView(eventyears);
    }

Upvotes: 0

Views: 2098

Answers (5)

Manish Parmar
Manish Parmar

Reputation: 859

You can try this code.

var eventyears = storeDB.EventMasters.Distinct(q => q.EventYear.).ToList().OrderByDescending(c => c.EventYear);

return PartialView(eventyears);

Upvotes: 0

Ajay
Ajay

Reputation: 6590

Try this

var eventyears = storeDB.EventMasters.ToList()
                       .OrderByDescending(c => c.EventYear == c.EventYear).Distinct();

Upvotes: 0

Tilak
Tilak

Reputation: 30698

Try following

var eventyears = storeDB.EventMasters
                     .GroupBy(c=>c.EventYear)
                     .Select(items=>items.First())
                     .SelectMany(item->item)
                       .ToList()
                       .OrderByDescending(c => c.EventYear == c.EventYear.Distinct());

it will take distinct items (based on EventYear). (it is possible to have items with same EventYear classified as same, even though they have different values for some other properties)

Upvotes: 0

Aravind
Aravind

Reputation: 1549

Try like this

var eventyears = from Data in storeDB.EventMasters
                         where (this == that) // Write your Logic
                         select Data;

        if (eventyears != null)
        {
            /// do your code,,.,,,
        }

Upvotes: 0

MarcinJuraszek
MarcinJuraszek

Reputation: 125620

I want to select unique or distinct EventYear

Isn't it just:

var eventyears = storeDB.EventMasters
                        .Select(c => c.EventYear)
                        .Distinct()
                        .ToList();

Upvotes: 3

Related Questions