在字符串列表中查找常用项

时间:2014-12-09 06:26:32

标签: c# linq

您好我拥有包含字符串列表的所有列表我想在这些字符串列表中查找常用项目 我试过了

var intersection = allLists
  .Skip(1)
  .Aggregate(
  new HashSet<string>(allLists.First()),
  (h, e) => { h.IntersectWith(e); return h);`

以及交叉(索引的硬代码列表)当我尝试

时,所有这些都无法正常工作
var inter = allLists[0].Intersect(allLists[1]).Intersect(allLists[2])
     .Intersect(allLists[3]).ToList();

foreach ( string s in inter) Debug.WriteLine(s+"\n ");

那么我将如何动态地执行此操作并在列表中获取常见的字符串项; 有没有办法避免Linq?

2 个答案:

答案 0 :(得分:2)

这不是最简单的方法吗?

var stringLists = new List<string>[] 
    { 
        new List<string>(){ "a", "b", "c" },
        new List<string>(){ "d", "b", "c" },
        new List<string>(){ "a", "e", "c" }
    };

var commonElements =
    stringLists
        .Aggregate((xs, ys) => xs.Intersect(ys).ToList());

我得到一个只有"c"的列表。

如果每个列表中的元素都可以重复,这也会处理这种情况。

答案 1 :(得分:0)

我会这样做:

class Program
{
    static void Main(string[] args)
    {
        List<string>[] stringLists = new List<string>[] 
        { 
            new List<string>(){ "a", "b", "c" },
            new List<string>(){ "d", "b", "c" },
            new List<string>(){ "a", "e", "c" }
        };

        // Will contian only 'c' because it's the only common item in all three groups.
        var commonItems = 
            stringLists
            .SelectMany(list => list)
            .GroupBy(item => item)
            .Select(group => new { Count = group.Count(), Item = group.Key })
            .Where(item => item.Count == stringLists.Length);

        foreach (var item in commonItems)
        {
            Console.WriteLine(String.Format("Item: {0}, Count: {1}", item.Item, item.Count));
        }
        Console.ReadKey();
    }
}

如果项目出现在所有组中,则该项目是一个公共项目,因此其计数必须等于组数量的条件:

.Where(item => item.Count == stringLists.Length)

编辑:

我应该在问题中使用HashSet之类的。对于列表,您可以将SelectMany行替换为此列:

.SelectMany(list => list.Distinct())
相关问题