KratosMafia
KratosMafia

Reputation: 333

Combining 2 lists of diffrent types into 1 based on an ID using LINQ

Hello so I'm trying to combine these 2 lists into 1.

List<Entry> testing = new List<Entry>();
List<Tool> yes = new List<Tool>();

foreach (var p in _context.Tool
   .Join(_context.Entry, 
         o => o.ToolId, 
         od => od.FktoolId, 
         (o, od) => new { o.Name, od.Measure, od.RunDate, od.User, od.V }))
{
    testing.Add(new LogEntries { 
      Measure = p.Measure, 
      V = p.V, 
      RunDate = p.RunDate, 
      User = p.User});

    yes.Add(new Tool { 
      Name = p.Name });
}

So I'm taking these 2 lists because I want the Name from one table to join with the other table. I'm then taking the list and turning it into JSON

ViewBag.Testing = JsonConvert.SerializeObject(testing);

I'm only getting the data from testing list but I want the Name from list "yes" into list "testing" based on the tool ids.

So can I just push the name into the list or is there a way to merge them. Since they are diffrent types I can't concat or intersect.

So the Data I'm pulling now is

[{ Measure : "1",

V : 3,

RunDate: "08/12/19",

User: "Test User"}]

And I'm wanting it to look like this

[{ Measure : "1",

V : 3,

RunDate: "08/12/19",

User: "Test User",

Name: "Dragon"}]

Upvotes: 2

Views: 56

Answers (1)

Brian Rogers
Brian Rogers

Reputation: 129717

In your Join statement you are already creating combined objects. Why don't you just put those combined objects in a list and serialize that?

var list = _context.Tool
    .Join(_context.Entry, 
          o => o.ToolId, 
          od => od.FktoolId, 
          (o, od) => new { od.Measure, od.V, od.RunDate, od.User, o.Name })
    .ToList();

ViewBag.Testing = JsonConvert.SerializeObject(list);

Upvotes: 2

Related Questions