2

我对这个问题的适当标题有问题,因为我有有趣的排序问题想要解决。

所以,我定义了 3 个类型的对象user { skill: level }

a { s1: 1, s2: 2, s3: 4 }
b { s1: 2, s2: 2, s3: 4 }
c { s1: 1, s2: 5, s3: 9 }

现在我想对用户进行排序ab并按c所选技能的总和。选择技能是s1s2。我不在乎s3

过滤器的排序结果[s1,s2]应该是[c,b,a]因为

s1 + s2 for c = 6, 
            b = 4, 
            a = 3

我已经为这种情况定义了类:

class Skill
{
    public string Name { get; set; }
    public int Level { get; set; }
}

class User
{
    public string Name { get; set; }
    public IList<Skill> Skills { get; set; }            
}

并初始化它:

var a = new User
            {
                    Name = "a",
                    Skills = new List<Skill>
                                {
                                    new Skill {Name = "s1", Level = 1},
                                    new Skill {Name = "s2", Level = 2},
                                    new Skill {Name = "s3", Level = 4}
                                }
                };
var b = new User
            {
                    Name = "b",
                    Skills = new List<Skill>
                                {
                                    new Skill {Name = "s1", Level = 2},
                                    new Skill {Name = "s2", Level = 2},                                              
                                    new Skill {Name = "s3", Level = 4}
                                }
                };
var c = new User
            {
                Name = "c",
                Skills = new List<Skill>
                                {
                                    new Skill {Name = "s1", Level = 1},
                                    new Skill {Name = "s2", Level = 5},
                                    new Skill {Name = "s3", Level = 9}
                                }
            };

下面我有用户列表和我想用于排序的技能列表:

var users = new List<User> {a, b, c};
var filters = new List<string> { "s1", "s2" };

我想收到

var selected = users.Magic(); // which results in [c,b,a]

我想使用 linq 和 ravendb 来做到这一点。显然,我不想将所有数据从数据库加载到内存中,然后进行魔术排序之类的事情。我想我需要用 map reduce 创建一些疯狂的索引,然后对这些索引进行一些 linq 查询等等......帮助?

顺便说一句:我正在使用 RavenDB - Build #960

编辑:

不幸的是,我的临时解决方法是将所有用户数据读入内存并使用 linq-to-objects(因为与 raven linq 驱动程序相关的问题,该驱动程序在查询期间不支持计算):

var selected = users.OrderByDescending(user =>
                                user.Skills
                                    .Where(skill => filters.Contains(skill.Name))
                                    .Select(skill => skill.Level)
                                    .Sum());
4

2 回答 2

0

创建一个在索引时执行此求和的索引并公开结果

from user in docs.Users
select new
{
    Skills_Sum = user.Skills.Sum(x=>x.Level)
}
于 2012-08-22T07:17:29.603 回答
0
var query = users.OrderBy(user => 
    user.Skills
    .Where(skill => skill.Name == "s1" || skill.Name == "s2")
    .Select(skill => skill.Level)
    .Sum());
于 2012-08-21T14:42:02.770 回答