尝试创建Sort方法时,IEnumerable可能有多个枚举

时间:2018-09-04 11:44:04

标签: c#

我创建了3种方法:

public IOrderedEnumerable<JObject> SortByImportance(IOrderedEnumerable<JObject> products)
{
    if (products == null) throw new ArgumentNullException(nameof(products));

    var firstProduct = products.First();
    return !firstProduct.ContainsKey("importance") ? 
        products : 
        products.OrderByDescending(m => m["importance"]);
}

public async Task<IOrderedEnumerable<JObject>> SortByPriorityAsync(string categoryId, IOrderedEnumerable<JObject> products, List<Answer> answers)
{
    if (string.IsNullOrEmpty(categoryId)) throw new ArgumentNullException(nameof(categoryId));
    if (products == null) throw new ArgumentNullException(nameof(products));
    if (answers == null) throw new ArgumentNullException(nameof(answers));

    var questions = await _questionProvider.Value.ListAsync(categoryId);
    if (questions == null) throw new ArgumentNullException(nameof(questions));
    if (questions.Count == 0) throw new ArgumentException(nameof(questions));

    foreach (var answer in answers)
        answer.Question = questions.SingleOrDefault(m => m.Id == answer.QuestionId);

    var sortedAnswers = answers.OrderBy(m => m.Question.Priority);
    return sortedAnswers.Aggregate(products, (current, answer) => current.ThenByDescending(m => m[answer.Question.Text.ToLower()].ToString().Equals(answer.Text, StringComparison.OrdinalIgnoreCase)));
}

public async Task<IOrderedEnumerable<JObject>> SortBySortationAsync(string categoryId, IOrderedEnumerable<JObject> products)
{
    if (string.IsNullOrEmpty(categoryId)) throw new ArgumentNullException(nameof(categoryId));
    if (products == null) throw new ArgumentNullException(nameof(products));

    var sortations = await _sortationProvider.Value.ListAsync(categoryId);
    if (sortations == null) throw new ArgumentNullException(nameof(sortations));
    if (sortations.Count == 0) throw new ArgumentException(nameof(sortations));

    var orderedSortations = sortations.OrderBy(m => m.Order);

    return orderedSortations.Aggregate(products, (current, sortation) => current.ThenByDescending(m => m[sortation.Field].ToString().Equals(sortation.Expression)));
}

可以按顺序调用这三种方法来更改产品列表的顺序。 例如:

var orderedProducts = products.OrderBy(a => 1);
orderedProducts = await sortProvider.SortBySortationAsync(categoryId, orderedProducts);
orderedProducts = await sortProvider.SortByPriorityAsync(categoryId, orderedProducts, answers);
orderedProducts = sortProvider.SortByImportance(orderedProducts);

这很好,我的单元测试表明排序很好,但是在SortByImportance方法中,它说明:

  

IEnumerable的可能的多重枚举

products.First()调用上。 谁能告诉我如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

如果这是理想的行为,则可以随时通过适当的注释来消除警告。

或者,您可以采取以下措施:

dialect

警告仍然存在,但第二排序将是排序的最佳方案,从而导致将IEnumerable轻松转换为IOrderedEnumerable(可能使用一个枚举)。

答案 1 :(得分:0)

尝试<%= f.input :header_or_shortDescription_cont_any %>