我对这个问题的适当标题有问题,因为我有一个有趣的排序问题我想解决。
因此,我定义了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 }
现在,我想根据所选技能的总和对用户a
,b
和c
进行排序。选择技能为s1
和s2
。我不关心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());
答案 0 :(得分:0)
var query = users.OrderBy(user =>
user.Skills
.Where(skill => skill.Name == "s1" || skill.Name == "s2")
.Select(skill => skill.Level)
.Sum());
答案 1 :(得分:0)
创建一个索引,在索引时执行此求和并公开结果
from user in docs.Users
select new
{
Skills_Sum = user.Skills.Sum(x=>x.Level)
}