日期:2014-05-17  浏览次数:20815 次

请问,如果取集合交集
给定有一个List<List<string>>类型的集合,求此集合里面的所有元素(List<string>)的交集

请问,该怎么写?用Linq方法语法查询
------最佳解决方案--------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            List<List<string>> data = new List<List<string>>()
            {
                new List<string>() { "1", "2", "3", "8" },
                new List<string>() { "1", "3", "5", "8" },
                new List<string>() { "1", "2", "5", "8" },
                new List<string>() { "1", "2", "3", "4", "5", "7", "8" }
            };
            var query = data.Aggregate((pre, curr) => pre.Intersect(curr).ToList());
            foreach (var item in query)
            {
                Console.WriteLine(item);
            }
        }
    }
}


1
8
Press any key to continue . . .
------其他解决方案--------------------
要写法简单,可以:

var result = lists.Aggregate(lists.First().AsEnumerable(), (a, l) => a.Intersect(l));

------其他解决方案--------------------

        static void Main(string[] args)
        {
            List<List<string>> list = new List<List<string>>();

            List<string> strs = new List<string>();
            strs.Add("shen");
            strs.Add("bao");
            strs.Add("zheng");
            list.Add(strs);

            strs = new List<string>();
            strs.Add("shen");