按主要顺序从json中出现的大多数字符串进行排序,并且顺序包含数组本身

时间:2019-06-17 20:18:44

标签: c# json asp.net-mvc entity-framework linq

我有一个JSON文件,其中包含与

相同的键作为数组的订单
[
   {
      "order":["Order1"]
   },
   {
      "order":["Order2"]
   },
   {
      "order":["Order2","Order3"]
   },
   {
      "order":["Order1","Order2"]
   },
   {
      "order":["Order2","Order3"]
   }
]

我希望它按大多数发生的订单组合进行订购。

请帮助我。

注意:这不是一个简单的字符串数组,请在将其标记为可能重复之前先查看json。

1 个答案:

答案 0 :(得分:1)

这可以如下进行。首先,为您的订单介绍一个数据模型,如下所示:

class Collection extends Array {
  constructor(array) {
    // call the constructor of the Array class
    super(array.length);

    // copy the values from `array` onto `this`;
    Object.assign(this, array);
  }

  clear() {
    // that's all it takes to empty an Array
    this.length = 0;
  }
}


var c = new Collection([1, 2, 3]);
console.log(c);

c.clear();
console.log(c);

接下来,为枚举定义以下相等比较器:

public class Order 
{
    public string[] order { get; set; }
}

现在,您可以反序列化包含上面列出的订单的JSON,并按降序对唯一订单进行排序,如下所示:

public class IEnumerableComparer<TEnumerable, TElement> : IEqualityComparer<TEnumerable> where TEnumerable : IEnumerable<TElement>
{
    //Adapted from IEqualityComparer for SequenceEqual
    //https://stackoverflow.com/questions/14675720/iequalitycomparer-for-sequenceequal
    //Answer https://stackoverflow.com/a/14675741 By Cédric Bignon https://stackoverflow.com/users/1284526/c%C3%A9dric-bignon 
    public bool Equals(TEnumerable x, TEnumerable y)
    {
        return Object.ReferenceEquals(x, y) || (x != null && y != null && x.SequenceEqual(y));
    }

    public int GetHashCode(TEnumerable obj)
    {
        // Will not throw an OverflowException
        unchecked
        {
            return obj.Where(e => e != null).Select(e => e.GetHashCode()).Aggregate(17, (a, b) => 23 * a + b);
        }
    }
}

演示小提琴here

或者,如果您想保留重复项而不是合并它们,则可以执行以下操作:

var items = JsonConvert.DeserializeObject<List<Order>>(jsonString);

//Adapted from LINQ: Order By Count of most common value
//https://stackoverflow.com/questions/20046563/linq-order-by-count-of-most-common-value
//Answer https://stackoverflow.com/a/20046812 by King King https://stackoverflow.com/users/1679602/king-king
var query = items
    //If order items aren't already sorted, you need to do so first.
    //use StringComparer.OrdinalIgnoreCase or StringComparer.Ordinal or StringComparer.CurrentCulture as required.
    .Select(i => i.order.OrderBy(s => s, StringComparer.Ordinal).ToArray()) 
    //Adapted from writing a custom comparer for linq groupby
    //https://stackoverflow.com/questions/37733773/writing-a-custom-comparer-for-linq-groupby
    //Answer https://stackoverflow.com/a/37734601 by Gert Arnold https://stackoverflow.com/users/861716/gert-arnold
    .GroupBy(s => s, new IEnumerableComparer<string [], string>())
    .OrderByDescending(g => g.Count())
    .Select(g => new Order { order = g.Key } );

var sortedItems = query.ToList();

演示小提琴#2 here

注意:

  • 我使用两个通用类型var query = items //If order items aren't already sorted, you may need to do so first. //use StringComparer.OrdinalIgnoreCase or StringComparer.Ordinal or StringComparer.CurrentCulture as required. .Select(i => i.order.OrderBy(s => s, StringComparer.Ordinal).ToArray()) //Adapted from writing a custom comparer for linq groupby //https://stackoverflow.com/questions/37733773/writing-a-custom-comparer-for-linq-groupby //Answer https://stackoverflow.com/a/37734601 by Gert Arnold https://stackoverflow.com/users/861716/gert-arnold .GroupBy(s => s, new IEnumerableComparer<string [], string>()) .OrderByDescending(g => g.Count()) .SelectMany(g => g) .Select(a => new Order { order = a }); 而不是this answer IEqualityComparer for SequenceEqual 中的IEnumerableComparer<TEnumerable, TElement> : IEqualityComparer<TEnumerable> where TEnumerable : IEnumerable<TElement>定义相等比较器Cédric Bignon,以防止通过IEnumerableComparer<string> lambda表达式中的类型推断将string []排序键向上转换为IEnumerable<string>

  • 如果您确定订单已经排序,或者.GroupBy(s => s, new IEnumerableComparer<string>())["Order3", "Order1"]不同,请仅将["Order1", "Order3"]替换为i.order.OrderBy(s => s, StringComparer.Ordinal).ToArray()

    < / li>