更好的方法(使用LINQ)?

时间:2017-06-03 19:33:04

标签: c# linq

我正在比较两个列表,在一种情况下,我从一个列表中删除不常见的元素(从具有更多元素的列表中删除),在另一种情况下(else语句)我将不常见的元素添加到一个列表中(添加到列表中的元素较少)

我能够使用下面给出的代码执行此操作,但我希望以更简洁的方式使用LINQ实现此目的。请建议我一个等效的LINQ代码

if (receivedList.Count < AuthorFacets.Count)
{
    for (int i = AuthorFacets.Count - 1; i >= 0; i--)
    {
        if (!receivedList.Contains(AuthorFacets[i]))
            AuthorFacets.RemoveAt(i);
    }
}
else
{
    for (int i = 0; i < receivedList.Count; i++)
    {
        if (!AuthorFacets.Contains(receivedList[i]))
            AuthorFacets.Add(receivedList[i]);
    }
}

2 个答案:

答案 0 :(得分:3)

使用linq你可以尝试这个

if (receivedList.Count < AuthorFacets.Count)
{
  AuthorFacets.RemoveAll(a=>!receivedList.Contains(a))
}
else
{
  AuthorFactets.AddRange(receivedList.Where(r=> !AuthorFacets.Contains(r)))
}

答案 1 :(得分:1)

这个怎么样?

using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main()
    {
        var receivedList = new List<string>();
        var AuthorFacets = new List<string>();

        receivedList.Add("2");
        receivedList.Add("4");
        receivedList.Add("6");

        AuthorFacets.Add("1");
        AuthorFacets.Add("2");
        AuthorFacets.Add("3");


        if (receivedList.Count < AuthorFacets.Count)
        {
            AuthorFacets = AuthorFacets.Where(i => receivedList.Contains(i)).ToList();
        }
        else
        {
            AuthorFacets.AddRange(receivedList.Where(i => !AuthorFacets.Contains(i)));
        }

        Console.WriteLine(string.Join("\n",AuthorFacets));
    }
}

源代码:https://dotnetfiddle.net/Hz8anK