Reputation: 1620
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]);
}
}
Upvotes: 0
Views: 72
Reputation: 4024
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)))
}
Upvotes: 3
Reputation: 21617
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
Upvotes: 1