c# – 部分取消组合重复值列表
发布时间:2020-12-15 08:07:09 所属栏目:百科 来源:网络整理
导读:我知道如何使用LINQ对数据进行分组,我知道如何将其拆分为单独的项目,但我不知道如何仅部分取消它. 我有一组看起来像这样的数据: var data = new DictionaryHeader,Detail(){ { new Header(),new Detail { Parts = new Liststring { "Part1","Part1","Part2"
我知道如何使用LINQ对数据进行分组,我知道如何将其拆分为单独的项目,但我不知道如何仅部分取消它.
我有一组看起来像这样的数据: var data = new Dictionary<Header,Detail>() { { new Header(),new Detail { Parts = new List<string> { "Part1","Part1","Part2" } } } }; 为了正确处理这个问题,我需要复制部分的每个实例都是字典中的单独条目(尽管它仍然是字典并不重要 – IEnumerable< KeyValuePair< Header,Detail>>完全可以接受) .但是,我不想完全拆分零件清单 – 列表中的不同部分是可以的. 具体来说,我希望最终数据看起来像这样: { { new Header(),"Part2" } } },{ new Header(),new Detail { Parts = new List<string> { "Part1" } } },} 对于更复杂的示例: var data = new Dictionary<Header,Detail>() { { new Header(1),{ new Header(2),{ new Header(3),"Part2","Part3","Part3"} } } }; var desiredOutput = new List<KeyValuePair<Header,Detail>>() { { new Header(1),{ new Header(1),"Part 3" } } },new Detail { Parts = new List<string> { "Part2","Part3" } } },new Detail { Parts = new List<string> { "Part2" } } } }; 任何建议? 解决方法
Linq在这里对你没什么帮助,但是这里有一个扩展方法,它可以解决这个问题:
public static IEnumerable<KeyValuePair<Header,Detail>> UngroupParts( this IEnumerable<KeyValuePair<Header,Detail>> data) { foreach (var kvp in data) { Header header = kvp.Key; List<string> parts = kvp.Value.Parts.ToList(); do { List<string> distinctParts = parts.Distinct().ToList(); Detail detail = new Detail() { Parts = distinctParts }; yield return new KeyValuePair<Header,Detail>(header,detail); foreach (var part in distinctParts) parts.Remove(part); } while (parts.Any()); } } 用法: var desiredOutput = data.UngroupParts(); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |