Addition and deletion of sub list from main list - c#

I have two lists such as Main List of type <T> and Sub List of same type
Now there are two conditions where
in one condition I want to remove the entire Sub List items from Main List and
in another condition just need to add all sub list items inside the Main list.
So far I have achieved this using the foreach loop, but now I just want to do it using LINQ concept.
Is there any way?

Thank you for posting your ideas, got the exact answer from #Sweeper idea, I just resolve this by using int type Lists, Here I am posting my answer,
`List<int> MainList = new List<int>() { 1, 2, 3, 4, 5 };
List<int> SubList = new List<int>() { 4,5};
MainList=MainList.Except(SubList).ToList();
MainList = MainList.Union(SubList).ToList();`

As per my understanding of your question,
List<Object> x = new List<Object>();
List<Object> y = new List<Object>();
if (somecondition)
{
x = x.Except(y).ToList();
}
else if (anotherCondition)
{
x = x.Concat(y).ToList();
}

Related

Adding list object inside a list C#

I'm new in c#. I just want to ask if it is possible to insert a list object inside a c# list just like in python? C# addrange only insert multiple item at once but not a list object.
For example:
lst = [[1,2,3],[4,5,6],[7,8,9]]
Yes, but is much more verbose than python.
As some comments already answered, you can use a List of List to create something like your python example:
List<List<int>> listOfLists = new List<List<int>>() { new List<int>() {1,2,3}, new List<int>() {4,5,6}, new List<int>() {7,8,9}};
You can also make a list of different objects just declaring it a List of Objects:
List<object> listOfObjects = new List<object>();
listOfObjects.Add(new List<int>() { 1, 2, 3 }); // Adding list of int
listOfObjects.Add("text"); // Adding string
listOfObjects.Add(new float[] { 1.42f, 51.7f}); // Adding array of float
listOfObjects.AddRange(listOfObjects); // Duplicating all the elements of listOfObjects
listOfObjects.AddRange(listOfLists); // Adding all elments of the list listOfLists
List AddRange is just a way of adding many elements at once inside a list.

Removing items from collection

I have a list of ids, and the items with these ids shall be removed from a Collection.
foreach(string id in list) {
myitemcollection.Remove(id); // This does not exist. How would I implement it?
}
Unfortunately, "Remove" takes a complete item, which I don't have, and "RemoveAt" takes an index, which I don't have either.
How can I achieve this? Nested loops will work, but is there a better way?
One way would be to use linq:
foreach(string id in list) {
//get item which matches the id
var item = myitemcollection.Where(x => x.id == id);
//remove that item
myitemcollection.Remove(item);
}
If mycollection is also a list of ints, you could use
List<int> list = new List<int> {1,2,3};
List<int> myitemcollection = new List<int> {1,2,3,4,5,6};
myitemcollection.RemoveAll(list.Contains);
If it is a custom class, lets say
public class myclass
{
public int ID;
}
you could use
List<int> list = new List<int> {1,2,3};
List<myclass> myitemcollection = new List<myclass>
{
new myclass { ID = 1},
new myclass { ID = 2},
new myclass { ID = 3},
new myclass { ID = 4},
new myclass { ID = 5},
new myclass { ID = 6},
};
myitemcollection.RemoveAll(i => list.Contains(i.ID));
List.RemoveAll Method
Removes all the elements that match the conditions defined by the
specified predicate.
Try using linq:
var newCollection = myitemcollection.Where(x=> !list.Contains(x.ID));
Please note that:
This assumes that your Item collection has data member called ID.
This is not the best performance wise...
If I understood your question rightly, try the below code snip
foreach (string id in list)
{
if (id == "") // check some condition to skip all other items in list
{
myitemcollection.Remove(id); // This does not exist. How would I implement it?
}
}
If this is not good enough. Make your question more clear to get exact answer
In terms of theory, you are dealing with a matter called closure.Within a loop (or for), you should make a copy of your list (or array or what you are iterating) in every way (that is mentioned differently by guys), mark those you want to remove and then deal with them out of the loop.

List<List<int>> Remove() method

I'd like to use Remove() method on list of lists, but it's not working for me.
Simple example should say everything:
List<List<int>> list = new List<List<int>>();
list.Add(new List<int> { 0, 1, 2 });
list.Add(new List<int> { 1, 2 });
list.Add(new List<int> { 4 });
list.Add(new List<int> { 0, 1, });
list.Remove(new List<int> { 1, 2 });
If I use RemoveAt(1) it works fine but Remove() not.
It is obviously the same reason that this code returns false:
List<int> l1 = new List<int>();
List<int> l2 = new List<int>();
l1.Add(1);
l2.Add(1);
bool b1 = l1 == l2; // returns False
bool b2 = l1.Equals(l2); // returns False too
So it seems to me that I cannot simply compare two lists or even arrays. I can use loops instead of Remove(), but there must be easier way.
Thanks in advance.
The problem is that List<T> doesn't override Equals and GetHashCode, which is what List<T> will use when trying to find an item. (In fact, it will use the default equality comparer, which means it'll use the IEquatable<T> implementation if the object implements it, and fall back to object.Equals/GetHashCode if necessary). Equals will return false as you're trying to remove a different object, and the default implementation is to just compare references.
Basically you'd have write a method to compare two lists for equality, and use that to find the index of the entry you want to remove. Then you'd remove by index (using RemoveAt). EDIT: As noted, Enumerable.SequenceEqual can be used to compare lists. This isn't as efficient as it might be, due to not initially checking whether the counts are equal when they can be easily computed. Also, if you only need to compare List<int> values, you can avoid the virtual method call to an equality comparer.
Another alternative is to avoid using a List<List<int>> in the first place - use a List<SomeCustomType> where SomeCustomType includes a List<int>. You can then implement IEquatable<T> in that type. Note that this may well also allow you to encapsulate appropriate logic in the custom type too. I often find that by the type you've got "nested" collection types, a custom type encapsulates the meaning of the inner collection more effectively.
First approach:
List<int> listToRemove = new List<int> { 1, 2 };
list.RemoveAll(innerList => innerList.Except(listToRemove).Count() == 0);
This also removes the List { 2, 1 }
Second approach (preferred):
List<int> listToRemove = new List<int> { 1, 2 };
list.RemoveAll(innerList => innerList.SequenceEqual(listToRemove));
This removes all lists that contain the same sequence as the provided list.
List equality is reference equality. It won't remove the list unless it has the same reference as a list in the outer list. You could create a new type that implements equality as set equality rather than reference equality (or you do care about order as well?). Then you could make lists of this type instead.
This simply won't work because you're tying to remove a brand new list (the new keyword kind of dictates such), not one of the ones you just put in there. For example, the following code create two different lists, inasmuch as they are not the same list, however much they look the same:
var list0 = new List<int> { 1, 2 };
var list1 = new List<int> { 1, 2 };
However, the following creates one single list, but two references to the same list:
var list0 = new List<int> { 1, 2 };
var list1 = list0;
Therefore, you ought to keep a reference to the lists you put in there should you want to act upon them with Remove in the future, such that:
var list0 = new List<int> { 1, 2 };
listOfLists.Remove(list0);
They are different objects. Try this:
List<int> MyList = new List<int> { 1, 2 };
List<List<int>> list = new List<List<int>>();
list.Add(new List<int> { 0, 1, 2 });
list.Add(MyList);
list.Add(new List<int> { 4 });
list.Add(new List<int> { 0, 1, });
list.Remove(MyList);
You need to specify the reference to the list you want to remove:
list.Remove(list[1]);
which, really, is the same as
list.RemoveAt(1);

C# Function Chaining

Why do i receive error in the following declaration ?
List<int> intrs = new List<int>().AddRange(new int[]{1,2,3,45});
Error :Can not convert type void to List ?
Because AddRange function does not return a value. You might need to perform this in two steps:
List<int> intrs = new List<int>();
intrs.AddRange(new int[]{1,2,3,45});
You could also use a collection initializer (assuming C# 3.0+).
List<int> intrs = new List<int> { 1, 2, 3, 45 };
Edit by 280Z28: This works for anything with an Add method. The constructor parenthesis are optional - if you want to pass thing to a constructor such as the capacity, you can do so with List<int>(capacity) instead of just List<int> written above.
Here's an MSDN reference for details on the Object and Collection Initializers.
Dictionary<string, string> map = new Dictionary<string, string>()
{
{ "a", "first" },
{ "b", "second" }
};
Because AddRange modifies the specified list instead of returning a new list with the added items. To indicate this, it returns void.
Try this:
List<int> intrs = new List<int>();
intrs.AddRange(new int[]{1,2,3,45});
If you want to create a new list without modifying the original list, you can use LINQ:
List<int> intrs = new List<int>();
List<int> newIntrs = intrs.Union(new int[]{1,2,3,45}).ToList();
// intrs is unchanged
AddRange does not return the list it has added items to (unlike StringBuilder). You need to do something like this:
List<int> intrs = new List<int>();
intrs.AddRange(new int[]{1,2,3,45});
AddRange() is declared as:
public void AddRange(object[]);
It does not return the list.
By the way in C# 3.x (not sure about 2.0) you can do either of
List<int> intrs = new List<int>{1,2,3,45};
List<int> intrs = new []{1,2,3,45}.ToList(); // with Linq extensions
Besides other answers, you can add your own extension method that will add range and return list (not that it's a good practice).
BTW, if you had already declared intrs, you could have done it with parentheses:
(intrs = new List<int>()).AddRange(new int[] { 1, 2, 3, 45 });
However, I like the initialization syntax better.
Although others have already mentioned that AddRange does not return a value, based on the samples given for alternatives it should also be remembered that the constructor of List will take an IEnumerable of T as well in addition to the code previously mentioned that is .NET 3.5+
For example:
List<int> intrs = new List<int>(new int[]{2,3,5,7});
There is yet another way.
List<int> intrs = new List<int>
{
1,
2,
3,
45
};

Can't append one list to another in C#... trying to use AddRange

Hi I'm trying to append 1 list to another. I've done it using AddRange() before but it doesn't seem to be working here... Here's the code:
IList<E> resultCollection = ((IRepository<E, C>)this).SelectAll(columnName, maxId - startId + 1, startId);
IList<E> resultCollection2 = ((IRepository<E, C>)this).SelectAll(columnName, endId - minId + 1, minId);
resultCollection.ToList().AddRange(resultCollection2);
I did debugging to check the results, here's what I got: resultCollection has a count of 4 resultCollection2 has a count of 6, and after adding the range, resultCollection still only has a count of 4, when it should have a count of 10.
Can anyone see what I'm doing wrong? Any help is appreciated.
Thanks,
Matt
When you call ToList() you aren't wrapping the collection in a List<T> you're creating a new List<T> with the same items in it. So what you're effectively doing here is creating a new list, adding the items to it, and then throwing the list away.
You'd need to do something like:
List<E> merged = new List<E>();
merged.AddRange(resultCollection);
merged.AddRange(resultCollection2);
Alternatively, if you're using C# 3.0, simply use Concat, e.g.
resultCollection.Concat(resultCollection2); // and optionally .ToList()
I would assume .ToList() is creating a new collection. Therefore your items are being added to a new collection that is immediately thrown away and the original remains untouched.
resultCollection.ToList() will return a new list.
Try:
List<E> list = resultCollection.ToList();
list.AddRange(resultCollection2);
Try
IList newList = resultCollection.ToList().AddRange(resultCollection2);
List<E> newList = resultCollection.ToList();
newList.AddRange(resultCollection2);
You can use any of the following:
List<E> list = resultCollection as List<E>;
if (list == null)
list = new List<E>(resultCollection);
list.AddRange(resultCollection2);
Or:
// Edit: this one could be done with LINQ, but there's no reason to limit
// yourself to .NET 3.5 when this is just as short.
List<E> list = new List<E>(resultCollection);
list.AddRange(resultCollection2);
Or:
List<E> list = new List<E>(resultCollection.Concat(resultCollection2));

Categories

Resources