我有一个customObject列表,我想将" CustomObject"通过CustomObject对象的List属性。
public class CustomObject
{
public string Name { get; set; }
public List<string> List { get; set; }
public CustomObject(string name, List<string> list)
{
this.Name = name;
this.List = list;
}
}
.....................
List<CustomObject> listCustomObject = new List<CustomObject>()
{
new CustomObject("A", new List<string>(){ "1","2","3", "4"} ),
new CustomObject("B", new List<string>(){ "4","8","5"}),
new CustomObject("C", new List<string>(){ "5","1","2", "4"})
};
期望的结果:
&#34; A&#34; /&#34; C&#34; =&GT;列表中的相同项目(&#34; 1&#34;,&#34; 2&#34;)
&#34; A&#34; /&#34; B&#34; /&#34; C&#34; =&GT;列表中的相同项目(&#34; 4&#34;)
&#34; B&#34; /&#34; C&#34; =&GT;列表中的相同项目(&#34; 5&#34;)
答案 0 :(得分:0)
使用某些扩展方法,您可以生成至少包含两个成员的所有输入组合:
public static IEnumerable<IEnumerable<T>> AtLeastCombinations<T>(this IEnumerable<T> elements, int minK) => Enumerable.Range(minK, elements.Count()+1-minK).SelectMany(k => elements.Combinations(k));
public static IEnumerable<IEnumerable<T>> Combinations<T>(this IEnumerable<T> elements, int k) {
return k == 0 ? new[] { new T[0] } :
elements.SelectMany((e, i) =>
elements.Skip(i + 1).Combinations(k - 1).Select(c => (new[] { e }).Concat(c)));
}
现在,您只需测试每个组合,看看它们是否有任何共同元素:
var ans = listCustomObject.AtLeastCombinations(2)
.Select(c => new { CombinationNames = c.Select(co => co.Name).ToList(), CombinationIntersect = c.Select(co => co.List).Aggregate((sofar, coList) => sofar.Intersect(coList).ToList()) })
.Where(ci => ci.CombinationIntersect.Count > 0)
.ToList();