我不能像下面这样查询一个集合,以获得给定 "key "的最大 "value",但key和value是一个集合的子集合。
我需要得到这个集合的 "Revision "键的最大值。
- document
- id
- description
- key
- version
- revision
- otherkey
- value
- "1.0"
- 1
- "othervalue"
- document
- id
- description
- key
- version
- revision
- otherkey
- value
- "1.0"
- 2
- "othervalue"
- document
- id
- description
- key
- version
- revision
- otherkey
- value
- "1.0"
- 3
- "othervalue"
- document
- id
- description
- key
- version
- revision
- otherkey
- value
- "2.0"
- 1
- "othervalue"
有什么提示吗?
使用linq Zip函数可以将这两个子数组合并为一个。下面是一个获取每个版本的最大修订值的例子。
void Main()
{
var data = GetData();
var maxRevisions = data
.Select(x => new { Document = x, KeyValue = x.Key.Zip(x.Value, (k, v) => new { Key = k, Value = v }) })
.GroupBy(x => new { Version = x.KeyValue.First(kv => kv.Key == "version").Value })
.Select(x => new { Version = x.Key.Version, MaxRevision = x.Max(y => y.KeyValue.First(kv => kv.Key == "revision").Value) })
.ToList();
maxRevisions.ForEach(mr => Console.WriteLine($"Version: {mr.Version} - MaxRevision: {mr.MaxRevision}"));
}
public class Document
{
public int Id { get; set; }
public string Description { get; set; }
public List<String> Key { get; set; }
public List<String> Value { get; set; }
}
public static List<Document> GetData()
{
return new List<Document> {
new Document {
Id = 1,
Description = "one-one",
Key = new List<string> { "version", "revision", "otherkey" },
Value = new List<string> { "1.0", "1", "othervalue" }
},
new Document {
Id = 1,
Description = "one-two",
Key = new List<string> { "version", "revision", "otherkey" },
Value = new List<string> { "1.0", "2", "othervalue" }
},
new Document {
Id = 1,
Description = "one-three",
Key = new List<string> { "version", "revision", "otherkey" },
Value = new List<string> { "1.0", "3", "othervalue" }
},
new Document {
Id = 1,
Description = "two-one",
Key = new List<string> { "version", "revision", "otherkey" },
Value = new List<string> { "2.0", "1", "othervalue" }
}};
}
这将输出以下结果:
Version: 1.0 - MaxRevision: 3
Version: 2.0 - MaxRevision: 1