Using LINQ to remove elements from a List<T>
Well, it would be easier to exclude them in the first place:
authorsList = authorsList.Where(x => x.FirstName != "Bob").ToList();
However, that would just change the value of authorsList
instead of removing the authors from the previous collection. Alternatively, you can use RemoveAll
:
authorsList.RemoveAll(x => x.FirstName == "Bob");
If you really need to do it based on another collection, I'd use a HashSet, RemoveAll and Contains:
var setToRemove = new HashSet<Author>(authors);
authorsList.RemoveAll(x => setToRemove.Contains(x));
Using LINQ to remove elements from a List<T> where Matching Items Take
var toRemove = exposur.Where(p => p.Campaigns.ID == Camp.Campaign.ID).Take(10).ToList();
exposur.RemoveAll(p => toRemove.Any(z => z == p));
Remove element from list using linq
When you copy the array to list and then apply linq, the link is only removing from the list, not from the array.
If you want to keep the array the same size, but with empty spaces, you should walk through the array using a for loop and set any that have x.type == "AUTO" to null.
for(int i = 0; i < completeOrder.Payments.Payment.Length; i++)
{
if(completeOrder.Payments.Payment[i].type == "AUTO")
{
completeOrder.Paymets.Payment[i] == null;
}
}
Otherwise, if you want the actual size of the array to change just set payment to the altered list. RemoveAll DOES NOT return the list (it returns void), so you might as well reverse your logic and just use a Where statement
completeOrder.Payments.Payment = completeOrder.Payments.Payment.Where(x => x.type != "AUTO").ToArray();
Removing items in List using LINQ
In this case you don't need LINQ but can just use List<T>.RemoveAll
instead
OrderLines.RemoveAll(x => ProductsToBeExcluded.Contains(x.ProductCode));
Remove a specific item from a list using LINQ
You cannot use a foreach
to remove items during enumeration, you're getting an exception at runtime.
You could use List.RemoveAll
:
list.RemoveAll(x => x.Number == 1);
or, if it's actually not a List<T>
but any sequence, LINQ:
list = list.Where(x => x.Number != 1).ToList();
If you are sure that there is only one item with that number or you want to remove one item at the maximum you can either use the for loop approach suggested in the other answer or this:
var item = list.FirstOrDefault(x => x.Number == 1);
if(item ! = null) list.Remove(item);
The link to the other question i have posted suggests that you can modify a collection during enumeration in C# 4 and later. No, you can't. That applies only to the new concurrent collections.
c# - How to remove matching items from a list using Linq or otherwise
You can use the GroupBy
method to group the items, and then return only the numbers from groups that have a count of 1
:
List<int> uniquePoints = points
.GroupBy(x => x) // Group all the numbers
.Where(g => g.Count() == 1) // Filter on only groups that have one item
.Select(g => g.Key) // Return the group's key (which is the number)
.ToList();
// uniquePoints = { 1, 2 }
How to Remove elements from one List based another list's element and condition?
You can remove the elements like this:
list1.RemoveAll(item => list2.Any(item2 => item.Key == item2.Key))
How to remove nested(child) items in List<> using Linq?
The items
property is an array, and you can't remove items from an array.
What you could do, is recursively select the MenuItem
s that you want to keep:
static IEnumerable<MenuItem> RecursiveSelect(this IEnumerable<MenuItem> items,
Func<MenuItem, bool> keep)
{
foreach (var item in items)
{
item.items = item.items?.RecursiveSelect(keep).ToArray();
if (keep(item)) yield return item;
}
}
Then use like this:
menu = menu.RecursiveSelect(x => !nameToRemove.Contains(x.text)).ToList();
Be aware that this creates a new List
rather than updating the existing List
.
Removing Elements From One List If not contained in another List. C#
Here's one way.
The following code will change Active
to false for chunks in activeChunks
that are not found in chunks
.
I assumed:
- chunks in both lists have an
Id
property - there are not chunks in
activeChunks
withActive==false
that you want to keep.
var chunksInActiveChunksThatDontExistInChunks =
activechunks.Where( ch => !chunks.Any( ch => ch.Id == chunk.Id ));
// Since it seems you're not familiar with Linq
// please be aware that this will not be evaluated until foreach is executed
// You can evaluate it earlier by calling ToList()
// e.g. var chunksIn... = activechunks.Where(...).ToList();
foreach( var chunk in chunksInActiveChunksThatDontExistInChunks )
{
chunk.Active = false;
}
activeChunks.RemoveAll(x => x.Active == false);
You could use Contains
if your object match, but I don't know if they do so I went with .Id
. It could be:
var chunksInActiveChunksThatDontExistInChunks =
activechunks.Where( ch => !chunks.Contains(ch));
For
//After Removing Chunks That do not exist in "chunks" add from chunks to ActiveChunks What is not In already in Chunks
you could:
var chunksThatAreInChunksButNotInActiveChunks =
chunks.Where( ch => !activeChunks.Any( ch => ch.Id == chunk.Id ));
activeChunks.AddRange(chunksThatAreInChunksButNotInActiveChunks);
Please note that this not good if the lists are modified by others while this is being executed.
Related Topics
How to Use a Class from One C# Project With Another C# Project
How to Set Datetimepicker to Month and Year Only Format
Could Not Start Windows Service, Error 1064
Null Value on Xml Deserialization Using [Xmlattribute]
Convert Time With Milliseconds to Datetime in C#
Regex to Match Alphanumeric and Spaces
Get All Children to One List - Recursive C#
How to Directly Print a Report Without Going Through Crystal Reports Viewer
Web API Returning Nested Json Values
Linq: Select an Object and Change Some Properties Without Creating a New Object
Controlling Datetime Parameter Formatting in Webapi 2
How Does Httpcontext.Current.User.Identity.Name Know Which Usernames Exist
Setting Connection String With Username and Password in Asp.Core MVC
How to Automatically Update an Application Without Clickonce
Asp.Net Core Get Json Array Using Iconfiguration