至少一个对象必须实现IComparable调用OrderBy

至少一个对象必须实现IComparable调用OrderBy

本文介绍了至少一个对象必须实现IComparable调用OrderBy()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了这个问题,但是我并没有从答案中找到幸福...

I already saw this question, but i didn't find my happiness with the answers...

我正在尝试这样做:

var coll = JsonConvert.DeserializeObject<ObservableCollection<ArticleJSON>>(json);
coll = coll.OrderBy(a => a.tags).Distinct().ToList();

引发错误:

此刻我没有找到解决方案,所以我做到了:

For the moment i didn't find the solution so i did that:

List<string> categories = new List<string>();
var coll = JsonConvert.DeserializeObject<ObservableCollection<ArticleJSON>>(json);

for (int i = 0; i < test.Count; ++i)
{
    for (int j = 0; j < test[i].tags.Count; ++j)
    {
        _categories.Add(test[i].tags[j]);
    }
}

categories = _categories.Distinct().ToList();

它有效,但是我很好奇为什么第一个不起作用.

It works but i'm curious to know why the first one don't work.

我的数据来自JSON:

My data come from a JSON :

            'tags': [

                                        'Pantoufle',
                                        'Patate'
                                     ]
                            },
            public List<string> tags { get; set; }

推荐答案

要订购一套东西,必须有一种比较两件事的方法,以确定哪一个更大或更小或者它们是否相等.任何实现IComparable接口的c#类型,都提供了将其与另一个实例进行比较的方法.

To order a set of things, there must be a way to compare two things to determine which one is larger, or smaller or whether they are equal. Any c# type that implements the IComparable interface, provides the means to compare it versus another instance.

您的tags字段是字符串列表.没有标准的方法可以以这种方式比较两个字符串列表.类型List<string>不实现IComparable接口,因此不能在LINQ OrderBy表达式中使用.

Your tags field is a list of strings. There is no standard way to compare two lists of strings in that manner. The type List<string> does not implement the IComparable interface, and thus cannot be used in a LINQ OrderBy expression.

例如,如果您想按标签数量订购商品,则可以这样操作:

If for example you wanted to order the articles by the number of tags, you could do that like this:

coll = coll.OrderBy(a => a.tags.Count).ToList();

因为Count将返回一个整数,并且该整数是可比较的.

because Count will return an integer and an integer is comparable.

如果要按排序顺序获取所有唯一标签,则可以这样操作:

If you wanted to get all unique tags in sorted order, you could do that like this:

var sortedUniqueTags = coll
    .SelectMany(a => a.Tags)
    .OrderBy(t => t)
    .Distinct()
    .ToList();

因为字符串是可比较的.

because a string is comparable.

如果您真的知道如何比较两个字符串列表,则可以编写自己的自定义比较器:

If you really know how to compare two lists of strings, you could write your own custom comparer:

public class MyStringListComparer : IComparer<List<string>>
{
    // implementation
}

并像这样使用它:

var comparer = new MyStringListComparer();
coll = coll.OrderBy(a => a.tags, comparer).Distinct().ToList();

这篇关于至少一个对象必须实现IComparable调用OrderBy()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 03:12