Two ArrayList manipulation - c#

I have one ArrayList in Session, lets say for example [305,306,380].
On submit, user choice other products which i save them in 2nd array, for example [390,305,480,380]
How can i make another three arrays where
All new values [390,480]
All values which are in both lists [305,380]
All values from list1 which are not in list2 [306]
I need this in ASP.NET 4.0 C#

You can use ArrayList.ToArray() to get arrays against your arraylists. Then using LINQ you can easily get what you want withExcept an Intersect methods, for example
array2.Except(array1)
array1.Except(array2)
array1.Intersect(array2)
Edit: Complete Code
According to your requirement, your code may look-like this;
ArrayList arrayList1 = new ArrayList(new int[] { 305, 306, 380 });
ArrayList arrayList2 = new ArrayList(new int[] { 390, 305, 480, 380 });
int[] array1 = (int[])arrayList1.ToArray(typeof(int));
int[] array2 = (int[])arrayList2.ToArray(typeof(int));
//1. All New values
int[] uniqueInArray2 = array2.Except(array1).ToArray();
//2. Common values
int[] commonValues = array1.Intersect(array2).ToArray();
//3. Values of arrayList1 which are not in arrayList2
int[] uniqueInArray1 = array1.Except(array2).ToArray();

Use HashSet the folowing way:
var first = new HashSet<int>();
first.Add(...);
var second = ...;
1. second.ExceptWith(first);
2. first.IntersectWith(second);
3. first.ExceptWith(second);

Related

C# list of array type

I want to create a list of array type.
I want to create array containing values :
array = [a,b];
Then i want to put this array in list :
List<Array> list = new List<Array>( );
I am able to do this with list of string type but no luck with array type :
List<String> list = new List<String>( );
I am from javascript background, not much familiar with concept of collections in c#.
Also how can i create array in c# like we do in javascript :
var arrTemp = ["a", "b"];
Well, since your array is string[]:
var arrTemp = ["a", "b"];
you have to declare the required list as List<string[]>:
// list of string arrays
List<string[]> list = new List<string[]>() {
new string[] {"a", "b"}
};
In case you want to be able to put any array into the list declare it as loose as possible (List<object[]>):
// list of abitrary arrays
List<object[]> list = new List<object[]>() {
new string[] {"a", "b"},
new double[] {123.45, 789.12, 333.55},
new object[] {'a', "bcd", 1, 244.95, true},
};
Hope this can help you
var test = new List<int[]>();
You can actually create a list of arrays:
var listOfArrays = new List<Array>();
The problem with this is that it's difficult to use the arrays themselves, as the Array type doesn't support array syntax. (e.g. You can't do listOfArrays[0][0]) Instead, you have to use the GetValue method to do your retrieval:
var obj = listOfArrays[0].GetValue(0);
But this has another problem. The GetValue method returns object, so while you could always cast it to the desired type, you lose your type safety in choosing this approach.
Alternatively, you could just store object[] arrays:
var listOfArrays = new List<object[]>();
var obj = listOfArrays[0][0];
But while this solves the issue of the array notation, you still lose the type safety.
Instead, if at all possible, I would recommend finding a particular type, then just have arrays of that type:
var listOfArrays = new List<string[]>();
string s = listOfArrays[0][0];
for example, an array of strings would be
var arrayOfString = new string[]{"a","b"};
// or shorter form: string[] arrayOfString = {"a","b"};
// also: var arrayOfString = new[] { "a", "b" }
And then creating a list-of-arrayOfString would be
var listOfArrayOfString = new List<string[]>();
This works with any type, for example if you had a class MyClass
var arrayOfMyClass = new MyClass[]{ ... }; // ... is you creating instances of MyClass
var list = new List<MyClass[]>();

Instantiating a List

If I want to instantiate a array the syntax is
int[] items = new int[] { 1, 2, 3 };
and the shortcut is
int[] items = {1,2,3};
Now I want to do the same to a List.
Question:
why does this work:
List<int> items = new int[] { 1, 2, 3 }.ToList();
but not this:
List<int> items = { 1, 2, 3 }; //invalid
or
List<int> items = { 1, 2, 3 }.ToList(); //invalid
The syntax
int[] array = {1,2,3};
is special syntactic sugar for array initialization. {1,2,3} is not itself an array yet.
This line
List<int> list = new[] {1,2,3}.ToList();
works because the expression new[] {1,2,3} returns an int[], which implements IEnumerable<int> and so you can call ToList() on it.
In the specs that's the difference between 12.6 Array initializers and 7.5.10.2 Array creation expressions.
List<T> has a constructor that takes an IEnumerable<T> as argument to initialize the list's content with. So you can either call
List<int> list = new List<int>(new[]{1,2,3});
or use the collection initializer syntax sugar:
List<int> list = new List<int> {1,2,3};
which is converted by the compiler to something like this:
var tmp = new List<int>();
tmp.Add(1);
tmp.Add(2);
tmp.Add(3);
List<int> list = tmp;

Is there something called array of list?

I declared something like this
List<double> close = new List<double>();
I pass this list to a function XYZ and the function will fill it up with value. As I need to run this XYZ function many times, is there a way to create a array of list so that I can access the third list element 7 by typing listarray[2][6].
I think you need something like this:
List<List<double>> list = new List<List<double>>();
var list1 = new List<double>();
list1.Add(1);
list1.Add(2);
var list2 = new List<double>();
list2.Add(3);
list2.Add(4);
list.Add(list1);
list.Add(list2);
var element = list[1][1];
The value of element will be the element of the second list at index of 1.
In this case, 4.
Thats about it:
List<double>[] arrayOfLists = new List<double>[200];
arrayOfLists[0] = new List<double>();
arrayOfLists[0].Add(5);
Console.WriteLine(arrayOfLists[0][0]);
Yes, just make either an array of lists (if you want it fixed sized), or a list of lists.
List<List<double>> items = new List<List<double>>();
List<double> close = new List<double>()
items.Add(close); //close is now element 0 in the outer list.
close.Add(1.23);
double result = items[0][0]; //result now equals 1.23

Removing items in Jagged array using index

I want to remove items of a Jagged array using indizes.
int[] toRemove; (e.g, {0, 1})
int[][] MainArray (e.g. { [0] {...}, [1] {...}, [2] {...}}
Expected result
int[][] result (e.g. {[2] {...}}
From the MainArray how to remove the items which having indexes from the toRemove list?
Is there an efficient way using LINQ?
Hopefully this gives the expected result:
var notInToRemove = MainArray
.Where((arr ,index) => !toRemove.Contains(index)).ToArray();
You could use the ElementAt method instead of the Remove method if all you want is the data that is not to be there in the toRemove set.
int[] toRemove = {0,1};
int[][] mainArray = new int[3][];
mainArray[0] = new int[]{0,0,0};
mainArray[1] = new int[]{1,1,1};
mainArray[2] = new int[]{2,2,2};
var result = mainArray.ElementAt(2); // This value 2 is found as all indexes of mainArray except the values in toRemove
//(Code would look like this :
Enumerable.Range(0, mainArray.Length).Except(toRemove);

Sorting an array related to another array

I have two arrays, x and y, where y is the value of the tens of every element in x. Now, I want to sort y. But, the order of y will be different of x's. So, I can't tell after sorting which element in y was related to, for instance, x[0].
I want a "double sorting" maybe.
Array.Sort has an overload that accepts two arrays; one for the keys, and one for the items. The items of both are sorted according to the keys array:
int[] keys = { 1, 4, 3, 2, 5 };
string[] items = { "abc", "def", "ghi", "jkl", "mno" };
Array.Sort(keys, items);
foreach (int key in keys) {
Console.WriteLine(key); // 1, 2, 3, 4, 5
}
foreach (string item in items) {
Console.WriteLine(item); // abc, jkl, ghi, def, mno
}
So in your case, it sounds like you want:
Array.Sort(y,x); // or Sort(x,y); - it isn't 100% clear
How about?
var selectedArr = new int[] { 1, 3, 5, 7, 9 };
var unorderArr = new int[] { 9, 7, 5, 3, 1 };
var orderedArr = unorderArr.OrderBy(o => selectedArr.IndexOf(o));
If we have two arrays of complex objects and want to sort them according to one of the two arrays then we can use the next approach:
// We want to sort "people" array by "Name" and
// accordingly to it reorder "countries" array.
Person[] people = new Person[]
{
new Person {Name = "Fill"},
new Person {Name = "Will"},
new Person {Name = "Bill"},
};
Country[] countries = new Country[]
{
new Country {Name = "Canada"},
new Country {Name = "UK"},
new Country {Name = "USA"}
};
// Here we sort "people" array, but together with each "Person"
// in sorted array we store its "index" in unsorted array. Then we
// will use this "index" to reorder items in "countries" array.
var sorted = people
.Select((person, index) => new {person, index})
.OrderBy(x => x.person.Name)
.ToArray();
// Here "people" array is sorted by "Name", and
// "contries" array is reordered accordingly to it.
people = sorted.Select(x => x.person).ToArray();
countries = sorted.Select(x => countries[x.index]).ToArray();
Another approach is to use overload of the method Array.Sort with IComparer. At first we should implement IComparer:
private class PeopleComparer : IComparer<Person>
{
public int Compare(Person x, Person y)
{
return x.Name.CompareTo(y.Name);
}
}
And then we can sort two our arrays:
Array.Sort(people, countries, new PeopleComparer());
Here is complete sample that demonstrates these two approaches.
If y is always the tens value of x, y probably shouldn't exist - you should probably just calculate it's value directly off of x when needed.
In general, sorting parallel arrays is only possible (without hand rolling a sort algorithm) when the sort algorithm takes a custom "swap" function, which you can implement in terms of swapping elements in both arrays simultaneously. std::sort in C++ and qsort in C don't allow this.
Also in the general case, consider a single array where the element is a pair of items, rather than a parallel array for each item. This makes using "standard" algorithms easier.

Categories