Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove set of items from ArrayList using LINQ

Tags:

c#

linq

I have Arraylist which contains all attribute's IDs (list1). Now I have another set of attribute's Ids (list2) which needs to be remove from first ArrayList (list1)

I am at beginner stage as LINQ developer so please suggest proper code snippet

Arraylist attributeIDs; // which contains Ids
int[] ids = { 1, 2, 3, 4 };
var id = ids.Select(s => s);
var sam = attributeIDs.Cast<IEnumerable>().Where(s => id.Contains(Convert.ToInt32(s)));
Arraylist filterAttributDs = Cast<Arraylist>sam;

After above code, I need to transfer output Arraylist to different methods so I need output in Arraylist only Thanks in advance!

like image 234
Sameer Wanwey Avatar asked Jun 11 '26 23:06

Sameer Wanwey


2 Answers

Try out the method

var sam = attributeIDs.Cast<IEnumerable>().Where(s => id.Contains(Convert.ToInt32(s)));
ArrayList myArrayList = new ArrayList(sam );

EDIT

int[] ids = { 1, 2, 3, 4 };
//var id = ids.Select(s => s);
List<int> id = ids.OfType<int>().ToList();
var list = attributeIDs.Cast<int>().ToList();
//or try 
//List<int> list = new List<int>(arrayList.ToArray(typeof(int)));
var sam = list.Where(s => id.Contains(s));
//if you want to remove items than , !Contains() rather an Contains()
// var sam = list.Where(s => !id.Contains(s); 
//also try out Intersect or Except instead of this as jon suggestion in comment 
//var sam= attributeIDs.Except(id); for diffence between list
//var sam= attributeIDs.Intersect(id); for common in list


ArrayList myArrayList = new ArrayList(sam );

combine all

check this for : LINQ to SQL in and not in

like image 176
Pranay Rana Avatar answered Jun 14 '26 14:06

Pranay Rana


new Arraylist((from id in attributeIDs where !ids.Contains(id) select id).ToList())

Like Jon mentioned though, you should consider just using a simple array or a generic collection. Also note that the above query runs in O(n*m) where n is the number of items in the original list and m is the number of elements in the list that you are trying to remove. You should consider using a HashSet and then using a set difference operation here for better performance.

like image 39
Ameen Avatar answered Jun 14 '26 14:06

Ameen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!