omid-ahmadpour
omid-ahmadpour

Reputation: 63

How to compare two lists

I have a list for answer that received from users like below:

List<UserAnswerToQue> lstGetUserAnswerIndex = new List<UserAnswerToQue>();

and class UserAnswerToQue is like below:

public class UserAnswerToQue
{
    int _Qu_Id;
    string _Title;

    public UserAnswerToQue(int qu_Id, string ans_Title)
    {
        _Qu_Id = qu_Id;
        _Title = ans_Title;
    }
 }

and have a list for true answer to the question:

var ListFinalTrueAnswer = (from x in FilteredTrueReceivedAnswerList
                                       select (x.qu_Id, x.ans_Title)).ToList();

The list ListFinalTrueAnswer contains Item1 and Item2

I want to find true answer that user gave to the questions and for that I need to compare two list lstGetUserAnswerIndex and ListFinalTrueAnswer. How to compare this two list and fine which answers is true?

Upvotes: 0

Views: 111

Answers (3)

Alexey
Alexey

Reputation: 1

Firstly, we can add public getters to our class. It's a better way to make fields private and access their values by public getters:

public class UserAnswerToQue 
{
    // ...
    public int Qu_Id => this._Qu_Id;
    public string Title => this._Title;
    // ...
}

Our dummy input list of answers:

List<UserAnswerToQue> lstGetUserAnswerIndex = new List<UserAnswerToQue>() {
    new UserAnswerToQue(1, "Water"),
    new UserAnswerToQue(2, "Metal"),
};

Your ListFinalTrueAnswer in second block of code is actually a List of tuples. This can be determined here:

select (x.qu_Id, x.ans_Title)

So, let us have a dummy list, that represents your list of tuples:

var ListFinalTrueAnswer = new List<Tuple<int, string>>() {
    new Tuple<int, string> (1, "Water"),
    new Tuple<int, string> (2, "Wood"),
};

Now we can check our dummy input list of answers:

lstGetUserAnswerIndex.Where(x => ListFinalTrueAnswer.Contains(new Tuple<int, string>(x.Qu_Id, x.Title)))

This kinda rich operation, so we can rewrite our query a little:

var ListFinalTrueAnswer2 = from x in FilteredTrueReceivedAnswerList select new { x.qu_Id, x.ans_Title }

We now have an IEnumerable of anonymous classes. And our list comparing:

lstGetUserAnswerIndex.Where(x => ListFinalTrueAnswer2.Any(y => (y.qu_Id == x.Qu_Id) && (y.ans_Title == x.Title)))

Upvotes: 0

Magnus
Magnus

Reputation: 46929

Create a hashset with the IDs of the true answer questions. (To get fast lookup)

var trueAnswers = ListFinalTrueAnswer.Select(x => (x.qu_Id, x.ans_Title)).ToHashSet();

Than filter your list using the hashset,

var userAnswers = lstGetUserAnswerIndex.Where(x => trueAnswers.Contains((x._Qu_Id, x._Title)));

Upvotes: 3

evilGenius
evilGenius

Reputation: 1101

var userTrueAnswer = lstGetUserAnswerIndex.Where(w=> ListFinalTrueAnswer.Any(a=>a.qu_Id == w.qu_Id && a.ans_Title == w.ans_Title));

Upvotes: 1

Related Questions