c#比较2列出<string>的逐行</string>

时间:2011-03-26 00:00:58

标签: c# .net

我有2个List数组。 1被称为“朋友”,另一个被称为“粉丝”。两个数组都包含大量的id号。我想逐行比较2个列表并创建一个新列表,其中包含两个列表中不会出现的项目。

这是我的代码:

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

        foreach (string friend in friends)
        {
            bool isfriend = false;
            foreach (string follower in followers)
            {
                if (friend == follower)
                {
                    isfriend = true;
                }
                if (isfriend)
                {
                    isfriend = false;

                }
                else
                {
                    notfollowingmelist.Add(friend);


                }
            }

        }

        MessageBox.Show(notfollowingmelist.Count.ToString());

我是否以正确的方式解决这个问题,还是有更好的途径来解决这个问题?

5 个答案:

答案 0 :(得分:7)

LINQ解决方案

两个列表中显示的数字:

friends.Intersect(followers);

出现在至少一个列表中的所有数字

friends.Union(followers);

列表中恰好一个的所有数字:

var intersectResult = friends.Intersect(followers);
var unionResult = friends.Union(followers);

var exactlyOnce = unionResult.Exclude(intersectResult);

这是你想要的吗?

答案 1 :(得分:4)

Linq是正确的方法,但这是另一种方法:

List<string> notFollowingMe = friends.Except(followers).ToList();

答案 2 :(得分:2)

我会使用类似快速排序的东西对两个列表进行排序,然后一起单步执行两个列表以确定哪些项目是唯一的。排序应该花费O(nlogn)时间,并且步进列表应该花费O(n)时间,总时间复杂度为O(nlogn)。您当前的实现需要O(n ^ 2)时间,这个时间较慢。

这是一些伪代码:

friends.qsort()
followers.qsort()
disjointList = new List()
int i=0
int j=0
while(i<friends.size() && j<followers.size()){
    if(friends[i] == followers[j]){
        i++
        j++
    }else if(friends[i] < followers[j]){
        disjointList.add(friends[i])
        i++
    }else{
        disjointList.add(followers[j])  // note: omit this line if you only want a list of friends that are not followers
        j++
    }
}

答案 3 :(得分:2)

IEnumerable<string> notFollowers = friends.Where(x => !followers.Contains(x));

BTW:您的代码不正确。

答案 4 :(得分:0)

(在VB.Net中)逻辑是一样的,应该可行。

For Each s As String In friends
    If Not (followers.Contains(s)) Then
        notfollowingmelist.Add(s)
    End If
Next
For Each s As String In followers
    If Not (friends.Contains(s)) Then
        notfollowingmelist.Add(s)
    End If
Next