简体   繁体   中英

Better way to do this ( using LINQ )?

I am comparing two lists and in one case I am removing the uncommon elements from one list ( removing from lists with more number of elements ) and in the other case (else statement) I am adding the uncommon elements to one list ( adding to list with lesser elements )

I am able to do this using the below given code but I was hoping to achieve this using LINQ in a more concise manner. Please suggest me an equivalent LINQ code

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]);
    }
}

Using linq you can try this

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

How about this?

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));
    }
}

Source Code: https://dotnetfiddle.net/Hz8anK

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM