C#按序列划分对编号进行排序

C#按序列划分对编号进行排序,c#,C#,我的数据如下: 五, 2. 2. 1. 3. 3. 四, 我希望输出为C#,如下所示: 一, 2. 3. 4. 5. 2. 三, 因此,基本上所有按ASC顺序排序的唯一值都是从剩余项开始的…我要说,这相当复杂。。。但它激起了我的兴趣。。。请注意,此解决方案非常简单。如果需要多字段排序或反向排序等,则会变得更复杂: public static class OrderByTest { private static int Increment<TKey>(Dictionary<

我的数据如下:

五, 2. 2. 1. 3. 3. 四,

我希望输出为C#,如下所示:

一, 2. 3. 4. 5. 2. 三,


因此,基本上所有按ASC顺序排序的唯一值都是从剩余项开始的…

我要说,这相当复杂。。。但它激起了我的兴趣。。。请注意,此解决方案非常简单。如果需要多字段排序或反向排序等,则会变得更复杂:

public static class OrderByTest
{
    private static int Increment<TKey>(Dictionary<TKey, int> dict, TKey key)
    {
        int value;

        if (dict.TryGetValue(key, out value))
        {
            value++;
        }

        dict[key] = value;
        return value;
    }

    public static IEnumerable<TSource> OrderByPartition<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
    {
        var dict = new Dictionary<TKey, int>();

        var res = source.Select(x => new { Value = x, Partition = Increment(dict, keySelector(x)) }).OrderBy(x => x.Partition).ThenBy(x => keySelector(x.Value));

        foreach (var value in res)
        {
            yield return value.Value;
        }
    }
}

它是一个Linq风格的解决方案,因此它生成一个新的有序序列,而不是像
Array.Sort
这样的就地解决方案。基本思想是将分区号添加到集合中。为了获得分区号,我们使用一个临时的
字典
,其中包含已找到的具有相同
TKey
的元素数。

您可以按值对数据进行分组,对组进行排序,然后在记住计数的情况下对组进行迭代-或者每次递减,当它们达到零时删除,或者增加一个计数器,只输出至少有那么多的内容。比如:

var values = new[] { 5, 2, 2, 1, 3, 3, 4 };
var data = new SortedDictionary<int, int>();
foreach(var val in values)
{
    int count;
    if (!data.TryGetValue(val, out count)) count = 0;
    data[val] = count + 1;
}

int lim = 0;
bool any;
do
{
    any = false;
    foreach (var pair in data)
        if (pair.Value > lim)
        {
            Console.WriteLine(pair.Key);
            any = true;
        }
    lim++;
} while (any);
var values=new[]{5,2,2,1,3,3,4};
var data=新的SortedDictionary();
foreach(值中的var val)
{
整数计数;
如果(!data.TryGetValue(val,out count))计数=0;
数据[val]=计数+1;
}
int lim=0;
布尔任何;
做
{
any=假;
foreach(数据中的var对)
如果(pair.Value>lim)
{
控制台写入线(配对键);
any=真;
}
lim++;
}而(任何);;

感谢您与我们分享。祝你有一个愉快的一天。我会说相当困难:-)现在我真的很感兴趣,如果已经有一个优化算法来解决这个问题…答案是快速排序吗?是吗?“所有唯一值排序第一”我只看到两个唯一的数字1和4。那么,为什么您预期的otuput不是
1 4 5 2 2 3 3
?确实相当优雅。有趣的是,一个人可以用LINQ做一些事情,并使其可读。
var values = new[] { 5, 2, 2, 1, 3, 3, 4 };
var data = new SortedDictionary<int, int>();
foreach(var val in values)
{
    int count;
    if (!data.TryGetValue(val, out count)) count = 0;
    data[val] = count + 1;
}

int lim = 0;
bool any;
do
{
    any = false;
    foreach (var pair in data)
        if (pair.Value > lim)
        {
            Console.WriteLine(pair.Key);
            any = true;
        }
    lim++;
} while (any);