我需要一些有关从列表字典创建新列表的帮助。处理必须以降序进行。我需要创建列表以链接可能发生的每种配对。
var mappings = new Dictionary<string, List<string>>
{
{ "Policy", new List<string> { "PlPolicy" } },
{ "Location", new List<string> { "L1", "L2" } },
{ "Claim", new List<string> { "C1", "C2", "C3" } }
};
foreach (var keyValuePair in mappings.OrderByDescending(x => x.Value.Count))
{
Console.WriteLine(@"Entity {0} has {1} items.", keyValuePair.Key, keyValuePair.Value.Count);
}
//I need to create lists that pair every kind of pairing that could happen.
//Example: (I think this is every iteration from the above dictionary)
//There are probably more here but this is just a sample.
var listOne = new List<string> {"C1", "L2", "PlPolicy"};
var listTwo = new List<string> {"C1", "L1", "PlPolicy"};
var listThree = new List<string> {"C2", "L2", "PlPolicy"};
var listFour = new List<string> {"C2", "L1", "PlPolicy"};
var listFive = new List<string> {"C3", "L1", "PlPolicy"};
var listSix = new List<string> {"C3", "L2", "PlPolicy"};
此刻我的大脑被卡住了,因此不胜感激...谢谢
答案 0 :(得分:2)
根据您的示例,您要查找的内容称为字典值的“ cartesian product”。埃里克·利珀特(Eric Lippert)撰写了一系列博客文章,内容涉及C#中包括one about the generation of cartesian products via a linq extension method的排列和组合集和序列的各种方式。
在引用的链接中,以下内容
public static class Program
{
static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnumerable<IEnumerable<T>> sequences)
{
IEnumerable<IEnumerable<T>> emptyProduct =
new[] { Enumerable.Empty<T>() };
return sequences.Aggregate(
emptyProduct,
(accumulator, sequence) =>
from accseq in accumulator
from item in sequence
select accseq.Concat(new[] { item }));
}
static void Main(string[] args)
{
var mappings = new Dictionary<string, List<string>> {
{ "Policy", new List<string> { "PlPolicy" } },
{ "Location", new List<string> { "L1", "L2" } },
{ "Claim", new List<string> { "C1", "C2", "C3" } }
};
foreach(var triple in CartesianProduct(mappings.Values)) {
Console.WriteLine( string.Join(" , ", triple) );
}
}
}
产生
PlPolicy , L1 , C1
PlPolicy , L1 , C2
PlPolicy , L1 , C3
PlPolicy , L2 , C1
PlPolicy , L2 , C2
PlPolicy , L2 , C3
答案 1 :(得分:0)
您只需使用LINQ对对象即可做到这一点。这是一个示例:
var mappings = new Dictionary<string, List<string>>
{
{ "Policy", new List<string> { "PlPolicy" } },
{ "Location", new List<string> { "L1", "L2" } },
{ "Claim", new List<string> { "C1", "C2", "C3" } }
};
var query = from policy in mappings["Policy"]
from location in mappings["Location"]
from claim in mappings["Claim"]
select new { Policy = policy, Location = location, Claim = claim };
var list = query.ToList();
foreach (var item in list)
{
Console.WriteLine($"{item.Policy} - {item.Location} - {item.Claim}");
}