为什么这个列表会出现排序错误?

Why is there a sorting error in this list?

我在图像和图像标签系统中有这些模型:

public class Image
{
    public int Id { get; set; }
    // some more properties...

    public List<ImageTag> Tags { get; set; }
}

public class ImageTag
{
    public int Id { get; set; }
    public int ImageId { get; set; }
    public string Tag { get; set; }
    public Image Image { get; set; }
}

要获得最常用标签的前 10 个列表,我 运行 这个查询:

List<ImageTag> mostUsedTags =
    await db.Images
        .Select(t => t.Tags.OrderBy(o => o.ImageId).FirstOrDefault()).Take(10)
        .ToListAsync().ConfigureAwait(false);

// The list has the tags with the fewest images first, so I have to reverse it:
mostUsedTags.Reverse();

我得到的列表包含以下数量的图像:4、3、2、1、2、1、1。

为什么第四名和第五名互换了位置?

The list has the tags with the fewest images first, so I have to reverse it:

您的假设不正确,在选择第一个元素之前,TagsImageId 执行以下命令,然后 返回 选择的任何顺序的列表。

t.Tags.OrderBy(o => o.ImageId)

我是 "guessing" 你想要这样的东西,虽然我不完全确定我完全理解你想要什么......

.Images.OrderByDescending(x => x.Tags.Count)
       .Select(t => ...)...

或者也许

ImageTags.GroupBy(x => x.ImageId)
         .OrderByDescending(x => x.Count)
         .Select(t => ...)
         .Take(10)

我不太清楚如何确定一个标签是否被多个图像使用,因为两个 类 之间的映射似乎有点 "muddy"(正如我在评论中所述在问题下)。

但是假设 Tag 属性 是 属性 我们用来查看两个 ImageTag 对象是否相同,那么你可以做类似的事情这是为了获得最常用的标签:

var mostUsedTags = images
    .SelectMany(i => i.Tags)           // Get all the ImageTags from all the images
    .GroupBy(t => t.Tag)               // Group them by the Tag property
    .OrderByDescending(g => g.Count()) // Order groups by their count (descending)
    .Take(10)                          // Take the top 10 results
    .Select(g => g.Count());           // Select the count associated with each tag

您还可以 select 提到 Tag 的字符串,这样您就可以判断哪些标签最受欢迎:

.Select(g => $"'{g.Key}' is associated with {g.Count()} images");

或者只是将 .Select() 替换为 .ToList() 以获得所有 IGrouping 对象本身的列表,因此您拥有与每个组关联的所有数据