I want to get list_ID value base on List_Position. How should I do? Thanks
List<int> list_ID = new List<int> (new int[ ] { 1, 2, 3, 4, 5 });
List<string> list_Position = new List<string> (new string[ ] { A, C, D, B, E});
A = 1,
B = 4,
C = 2,
D = 3,
E = 5,
Equals(Object) Method which is inherited from the Object class is used to check if a specified List<T> object is equal to another List<T> object or not. Syntax: public virtual bool Equals (object obj);
Java equals() method of List interface compares the specified object with the list for equality. It overrides the equals() method of Object class. This method accepts an object to be compared for equality with the list. It returns true if the specified object is equal to the list, else returns false.
Sort & Compare to check if two lists are equal If both are of different size then it means lists are not equal. Whereas, if both lists are of same size, then created a sorted versions of both the lists and compared them using == operator to check if lists are equal or not.
sort() and == operator. The list. sort() method sorts the two lists and the == operator compares the two lists item by item which means they have equal data items at equal positions. This checks if the list contains equal data item values but it does not take into account the order of elements in the list.
The best option for you at this moment is Dictionary Class with list_Position as key and list_Position as value So that you can access values based on position and wise Versa. the definition will be like the following:
Dictionary<int, string> customDictionary=
new Dictionary<int, string>();
customDictionary.Add(1,"A");
customDictionary.Add(2,"C");
....
If you want to access value corresponds o 2
means you can use
string valueAt2 = customDictionary[2]; // will be "C"
If you want to get the key/s corresponds to the specific value means you can use like the following:
var resultItem = customDictionary.FirstOrDefault(x=>x.value=="C");
if(resultItem !=null) // FirstOrDefault will returns default value if no match found
{
int resultID = resultItem.Key;
}
If you still want to go with two lists means you can consider this Example Which means, Get position of the required element from the list_Position
and get the element at this position in the list_ID list, Keep in mind list_ID must be greater or equal in number of elements as that of in the list_Position. The code will be like this:
string searchKey="D";
int reqPosition=list_Position.IndexOf(searchKey);
if(reqPosition!=-1)
{
Console.WriteLine("Corresponding Id is {0}",list_ID[reqPosition]);
}
else
Console.WriteLine("Not Found");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With