ViewModel Controller Query - Including a second property in a view

Dean Everhart 1,536 Reputation points
2023-05-06T14:47:22.7966667+00:00

Premise:

The controller code below displays the first field - PropertySet A, Property One and NOT the PropertySetB, Property One field (pictured below).

Question:
How does the code have to be altered to display both PropertySet A, Property One and PropertySetB, Property One?

Environment: Net Core 6 MVC, Visual Studio Community 2022 (64 bit), WIndows 11

            //define a variable to store the return data.
            var ab2 = new List<AB>();
            //query A and B table, 
            var Alist = _dbContext.A.ToList();
            var Blist = _dbContext.B.ToList();
            //use foreach statement to filter data. And Add A and B to the ab list.
            foreach (var item in Alist)
            {
                var newab = new AB()
                {
                    A = item
                };
                //add the new item into the list.
                ab2.Add(newab);
            }
            return View(ab2); // return the list to the view page.

User's image

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,673 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,538 questions
0 comments No comments
{count} votes

Accepted answer
  1. Bruce (SqlWork.com) 68,081 Reputation points
    2023-05-06T16:38:53.9+00:00

    you have two lists. you want to return a third list that is the combination of the two. what relates them together? that is, for each item in list A, what item in list B matches? once you figure that out its trivial:

    var Alist = _dbContext.A.ToList();
    var Blist = _dbContext.B.ToList();
    var ABList = Alist.Select(a => new AB
    {
        A = a,
        B = Blist.FirstOrDefault(b => b.???? = a.????)
    }).ToList();
     
    

    or just do a join and let the database do the work:

    var ABList = _dbContext.A.Join(_dbContext.B,
       a => a.????, 
       b => b.????, 
       (a, b) => new AB
       {
          A = a,
          B = b
       }).ToList();
    

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.