0

我有简单的类型Question

public class Question
{
    public string[] Tags { get; set; }
    public DateTime Created { get; set; }
}

虽然我有一个问题列表,但我需要沿着标签列表(称为过滤器)过滤它们。与过滤器列表匹配的标签最多的问题应该放在结果集合中的较高位置。我为此写了表达式:

public IList<Question> GetSimiliar(IList<Questions> all, string[] filters)
{
    var questions = all.Select(
                        x => new 
                               { 
                                  MatchedTags = x.Tags
                                                 .Count(tag => filters.Contains(tag)), 
                                  Question = x 
                               })
                       .Where(x => x.MatchedTags > 0)
                       .OrderByDescending(x => x.MatchedTags)
                       .Select(x => x.Question);

    return questions.ToList();
}

现在我需要对这种情况的支持,在这种情况下,我有多个问题具有相同数量的匹配标签。此类问题应按创建日期(从最新到最旧)进一步排序。

我想要的示例:

过滤器:标签 = [a,b,c]

要过滤的问题集合:

  1. q1 {标签 = [a],创建 = 1939 }
  2. q2 {标签 = [b],创建 = 1945 }
  3. q3 { 标签 = [a,b,c],创建 = 1800 }
  4. q4 { 标签 = [a,b],创建 = 2012 }
  5. q5 {标签 = [z],创建 = 1999 }

结果 - 排序后的集合:

  1. q3
  2. 第四季度
  3. q2
  4. q1

如何使用 linq 做到这一点?

4

2 回答 2

3

现在我需要对这种情况的支持,在这种情况下,我有多个问题具有相同数量的匹配标签。此类问题应按创建日期(从最新到最旧)进一步排序。

使用ThenByThenByDescending对查询进行进一步排序。使用这些方法打破之前订购的关系。

.OrderByDescending(x => x.MatchedTags)
.ThenByDescending(x => x.Question.Created)
.Select(x => x.Question); 
于 2012-04-06T15:35:03.990 回答
1

101 Linq Samples 页面有一个嵌套分组示例。此示例使用 group by 对每个客户的订单列表进行分区,首先按年份,然后按月份:

public void Linq43() 
{ 
    List<Customer> customers = GetCustomerList(); 

    var customerOrderGroups = 
        from c in customers 
        select 
            new 
            { 
                c.CompanyName, 
                YearGroups = 
                    from o in c.Orders 
                    group o by o.OrderDate.Year into yg 
                    select 
                        new 
                        { 
                            Year = yg.Key, 
                            MonthGroups = 
                                from o in yg 
                                group o by o.OrderDate.Month into mg 
                                select new { Month = mg.Key, Orders = mg } 
                        } 
            }; 

    ObjectDumper.Write(customerOrderGroups, 3); 
} 
于 2012-04-06T15:00:24.213 回答