0

I want to access the following in C# using LINQ:

var output = db.AuditLogDetails.Where(c => c.CostCenterID == id).Select(m => new History
{
    CostCenterID=(int)m.CostCenterID,
    CostCenterOwner=c.Owner // c is not accesible
});

I am unable to assign CostCenterOwner=c.Owner

Sujoy
  • 1,051
  • 13
  • 26
  • 3
    Try `m.Owner` c is unavailable since you have a `Select`. – panoskarajohn Jan 05 '20 at 12:44
  • 1
    Can you show us Class `AuditLogDetails`, `Owner` is a property of `AuditLogDetails`? if yes then `c` used in where clause predicate indicates single `AuditLogDetail` class and its scope is limited to **only** `where` clause. As you are doing `Select` after that you, now your `m` variable in `Select` referring single object of `AuditLogDetail` class. Instead of `c` you should use `m`.(c is not in scope of `Select`) – Prasad Telkikar Jan 05 '20 at 12:50
  • you should use a `join` – Stefan Jan 05 '20 at 12:50
  • Dear Prasad, as commented in the below answer, I am repeating, Owner is a property of `c` not `m`. Do I have to use `SelectMany`? Show me. – Sujoy Jan 05 '20 at 12:52
  • `.Where` points to the same objects as `.Select` only filtered by where. Where doesn't change the objects types. So in this case `m == c` – Charles Jan 05 '20 at 12:56
  • @Charles so why doesn't c# allow me to use `c` ? – Sujoy Jan 05 '20 at 13:01
  • Please share the class implementations. – Amir Molaei Jan 05 '20 at 13:01
  • @Sujoy It doesn't allow you to use c because c is in a different scope. c is a local variable for the `Where` function. Also `Select` is not a child of `where` you're just chaining two methods of an ienumerable. – Charles Jan 05 '20 at 13:08
  • @Charles now I agree with you. – Sujoy Jan 05 '20 at 18:14

1 Answers1

2

Where clause just Filters a sequence of values based on a predicate, then you are selecting value in Select clause with m predicate

So you can try this way

.Select(m => new History
{
    CostCenterID=(int)m.CostCenterID,
    CostCenterOwner= m.Owner
});
Nguyễn Văn Phong
  • 13,506
  • 17
  • 39
  • 56