2

I need equivalent LINQ to SQL query for the query written in access database. Below is the query in access database.

SELECT  Table1.ID, Table1.CODE, MIN (Table1.COST) 
FROM Table1 GROUP BY Table1.ID, Table1.CODE

In this query I get COST which is minimum to the given repeated CODE

Below query is giving error "Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access."

var ptQ = from i in
(from uh in ptTable
 select new
 {
     uh.ID, uh.CODE, uh.COST
 })

group i by new { i.ID, i.CODE }
into g

select new
{
    g.Key.ID, g.Key.CODE, g.Min(uh => uh.COST)
};
0

3 Answers 3

3

You need to specify the property name for the Min call:

select new {g.Key.ID, g.Key.CODE, MinimumCost = g.Min(uh=>uh.COST)};

The C# compiler will infer a name if the property value is a property or field access (as per ID and CODE), so the above is equivalent to:

select new { ID = g.Key.ID,
             CODE = g.Key.CODE,
             MinimumCost = g.Min(uh=>uh.COST) };

Personally I would specify the names everywhere if they're not idiomatic C# names otherwise:

select new { Id = g.Key.ID,
             Code = g.Key.CODE,
             MinimumCost = g.Min(uh=>uh.COST) };
Sign up to request clarification or add additional context in comments.

12 Comments

I interpret the MS guideline as referring to initialisms, so Id is valid ;p
@Marc: I actually checked the guidelines and they explicitly call out Id and Ok. Other two-letter acronyms/abbreviations would be fully upper case.
Of course, MS follow this religiously too ;p (points vaguely at the Min(...) method...)
@Marc: The Min method is fine - it's three letters... (But "id" is sometimes ID and sometimes Id.)
the 3-letter rule is capitalisation - I was meaning the abbreviation guidance, which advises against shortening. In the v7 documentation the example was GetWin vs GetWindow. I guess it comes down to a subjective call on Min vs Minimum - meh, I'm not going to worry about it ;p
|
1

You need to tell it what to call the last value in the anon-type (note that for direct member access members (g.Key.ID and g.Key.CODE) the name can be inferred (ID and CODE respectively):

select new {g.Key.ID, g.Key.CODE, MinCost = g.Min(uh=>uh.COST)};

You can also supply explicit names for the other members if you want:

select new {Id = g.Key.ID, Code = g.Key.CODE, MinCost = g.Min(uh=>uh.COST)};

Comments

0

You should be able to do it in one statement:

from i in Table1
group i by new { i.ID, i.CODE } into g
select new { g.Key.ID, g.Key.CODE, COST = g.Min(x => x.COST) }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.