简体   繁体   中英

LINQ Return DISTINCT Values

I have a LINQ to Entities query that I want to return only unique values of TagID and TagName.

Code:

var tags = (from t in _dbContext.TaskRecordDetails.ToList()
                       join tag in _dbContext.Tags on t.TagName equals tag.TagName
                       where t.Period == period
                       select new TagDTO()
                       {
                           TagID = tag.TagID,
                           TagName = tag.TagName
                       });

            return tags.Distinct<TagDTO>();

However, duplicate rows are still returned as below. How do I ensure only unique rows are returned?

[
    {
        "TagID": 1,
        "TagName": "Level 1",
        "TagDescription": null,
        "IsActive": false
    },
    {
        "TagID": 2,
        "TagName": "Level 3",
        "TagDescription": null,
        "IsActive": false
    },
    {
        "TagID": 3,
        "TagName": "Level 5",
        "TagDescription": null,
        "IsActive": false
    },
    {
        "TagID": 1,
        "TagName": "Level 1",
        "TagDescription": null,
        "IsActive": false
    },
    {
        "TagID": 2,
        "TagName": "Level 3",
        "TagDescription": null,
        "IsActive": false
    }
]

Based on your last comment, here is a solution:

var tags = (from t in _dbContext.TaskRecordDetails
            join tag in _dbContext.Tags on t.TagName equals tag.TagName
            where t.Period == period
            select tag).Distinct().ToList();

return tags.select(x => new TagDTO
{
    TagID = x.TagID,
    TagName = x.TagName
});

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