简体   繁体   中英

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);
    }

I want to select unique or distinct EventYear

Isn't it just:

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

Try like this

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

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

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)

Try this

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

You can try this code.

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

return PartialView(eventyears);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM