Click here to Skip to main content
15,867,308 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I am working on comparing two same indexes. Basically I am declaring two lists.

What I have tried:

C#
List<string> names = new List<string>() { "Bob", "Lara", "Andrew", "Adam" };
List<string> surnames = new List<string>() { "Dar", "Tars", "Vernik", "Smith" };



and I am generating a random of either names or surnames and displaying it:

C#
List<String> fullnames = names.Concat(surnames).ToList();
Random rand = new Random();
String randomname = fullnames[rand.Next(fullnames.Count)];

Console.WriteLine(randomname);


I was wondering how to compare an index in both of the lists that have been randomly generated.

For example next random is name Bob

So if
index 1 in names = bob
AND
index 1 in surnames = Dar

do something....

Any help would be apprciated
Posted
Updated 13-Nov-17 1:56am
v2

if i understood your requirement correctly then this would help, and i think there is no point of comparing two lists, the data is always different.

List<string> names = new List<string>() { "Bob", "Lara", "Andrew", "Adam" };
           List<string> surnames = new List<string>() { "Dar", "Tars", "Vernik", "Smith" };

           List<String> fullnames = names.Concat(surnames).ToList();
           Random rand = new Random();
           String randomname = fullnames[rand.Next(fullnames.Count)];

           int index = names.IndexOf(randomname); // check randomname is present in names list
           if (index == -1)  // not  in names list
               index = surnames.IndexOf(randomname);  // index of the random name in the surnames list

           string name = names[index];  // Bob
           string surname = surnames[index];// Dar
 
Share this answer
 
v3
Comments
fellanmorgh 13-Nov-17 7:58am    
Cool, was looking for something like that. Thanks for your help. :)
Karthik_Mahalingam 13-Nov-17 8:50am    
welcome :)
Suvendu Shekhar Giri 13-Nov-17 10:24am    
Great one! 5Ed!
Karthik_Mahalingam 13-Nov-17 10:27am    
Thank you SSG
Not correctly able to understand how/why you are generating the lists but having method something like following can help if you are trying to get the dissimilar items in the list, I believe-
C#
public IEnumerable<string> GetDifferences(List<string> list1, List<string> list2)
{
    for (int i = 0; i < list1.Count; i++)
    {
        if (list1[i] != list2[i]) yield return list1[i];
    }
}


ref: c# - Compare two List<string> by value and index - Stack Overflow[^]

According to your requirement, instead of returning the item, you can write the necessary logic in the IF block.

Hope, it helps :)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900