首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

请教,如果取集合交集

2012-12-15 
请问,如果取集合交集给定有一个ListListstring类型的集合,求此集合里面的所有元素(Liststring)的交

请问,如果取集合交集
给定有一个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");
            strs.Add("zheng");


            strs.Add("qiao");
            strs.Add("ling");
            list.Add(strs);

            strs = new List<string>();
            strs.Add("zheng");
            strs.Add("qiao");
            strs.Add("ling");
            list.Add(strs);

            List<string> result = new List<string>();

            for (int index = 0; index < list.Count; index++)
            {
                if (index == 0)
                    result = list[0];
                else
                    result = result.Intersect(list[index]).ToList();
            }

            result.ForEach(c => Console.WriteLine(c));
     
            Console.Read();   

            //结果为zheng
        }


[其他解释]
http://msdn.microsoft.com/zh-cn/library/bb460136.aspx
[其他解释]
http://wenku.baidu.com/view/b02c706c25c52cc58bd6be52.html
集合、数据的交集、差集

[其他解释]
LINQ的 Intersect

热点排行