Nisar Afridi
Nisar Afridi

Reputation: 157

Combine two different lists C#

i have two classes

public class AuditResults
    {
        public string ID { get; set; }
        public string Question { get; set; }
    }

public class AuditResults2
    {
        public int Channel_ID { get; set; }
        public bool Available_Item{ get; set; }
    }

AuditResults will have multiple rows returned from query, while AuditResults2 will have only one.

I want to combine there all results to something like

[
      {
      "ID": "1",
      "Question": "Question 1 here",
   },
      {
      "ID": "3",
      "Question": "Question 3 here",
   },
     "Channel_ID" : true,
     "Available_Item" : false
]

if i make a third class which contain both other classes objects, can i add 2 classes results in 3rd one.

public class AuditResultsFinal
    {
        public AuditResults AuditResults {get; set;}
        public AuditResults2 AuditResults2 { get; set; }
    }

Results of AuditResults

List<AuditResults> myResults = Database.SqlQuery<AuditResults>(query,model.UserName).ToList();

Results of AuditResults2

List<AuditResults2> myResults2 = Database.SqlQuery<AuditResults2>(query,model.UserName).ToList();

What to do here to combine above 2 results in myFinalResults:

List<AuditResultsFinal> myFinalResults = new List<AuditResultsFinal>();

Upvotes: 0

Views: 121

Answers (2)

Amit Kumar
Amit Kumar

Reputation: 5962

You need List of AuditResults in your final class. So You need to make it List type. Change your AuditResultsFinal as below

public class AuditResultsFinal
    {
        public List<AuditResults> AuditResults { get; set; }
        public List<AuditResults2> AuditResults2 { get; set; }
    }

Then You can assign List of AuditResults and AuditResults2 in your AuditResultsFinal.

var AuditResults1 = new List<AuditResults>{
                new AuditResults{ID="1",Question="Q1"},
                new AuditResults{ID="2",Question="Q2"}
            };

            var AuditResults2 = new List<AuditResults2>{
                new AuditResults2{Channel_ID=3,Available_Item=true},
                new AuditResults2{Channel_ID=4,Available_Item=false}
            };

            AuditResultsFinal final = new AuditResultsFinal()
            {
                AuditResults = AuditResults1,
                AuditResults2 = AuditResults2
            };

Upvotes: 1

Torben
Torben

Reputation: 478

Try this under the condition that you do not care about, which objects come together in AuditResultsFinal and that both Lists have the same length.

var result = new List<AuditResultsFinal>();

for(var i = 0; i < myResults.Count; i++)
{
   res.Add(new AuditResultsFinal() { AuditResults = myResults[i], AuditResults2 = myResults2[i] });
}

Upvotes: 0

Related Questions