Click here to Skip to main content
15,908,768 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i try to fetch data from one table first i create sql query and then i try to convert this sql to linq query

What I have tried:

C#
[WebMethod]
public static string GetVol()
{
try
{
TrackDataEntities1 DB = new TrackDataEntities1();
var a = DB.tblVeh;
string data = "[";
foreach (var p in a)
{
var re = (from vehvoila in DB.tblVeh
where vehvoila.MID.Equals("23065") && !(vehvoila.Name == "")
group vehvoila by new { vehvoila.Name } into g
select new
{
g.Key.Name ,
cnt = g.Select(t => t.Name ).Count()
});
}



data = data.Substring(0, data.Length - 1);
data += "]";
return data;
}

catch (Exception exception)
{
throw new Exception();

}

}


actual sql query is

SQL
Select Name, count(*) from tblVeh
WHERE MID = 23065 and Name <> '' Group By Name


data
C#
VName (No column name)
d1     2
s2     1
f3      2

now when i debug `'re'` shows

'System.Data.Objects.ObjectQuery<<>f__AnonymousType1<string,int>>}'
but i want data like this

['d1',2],['s2',1],['f3',20]

i fetch data only from one table
Posted
Updated 8-Jun-16 20:33pm
v2
Comments
Maciej Los 9-Jun-16 2:13am    
If i understand you well, you want to return string in this format: ['d1',2],['s2',1],['f3',20]. Am i right?
super_user 9-Jun-16 2:28am    
yes exaclty

1 solution

If you want to return a set of records, try this:
C#
string sMid = "23065";
var re = DB.tblVeh
           .Where(v=>v.MID.Equals(sMid) && v.Name != string.Empty)
           .GroupBy(v=>v.Name)
           .Select(g=> new
               {
                   Vname = g.Key.Name,
                    Count = g.Count()
               }).ToList();


Above code returns:
Vname   Count
d1      2
e3      5
g2      8


To be able to go through the resultset, you have to use foreach(...) loop:
C#
Console.WriteLine("Vname - Count");
foreach(var a in re)
{
    Console.WriteLine("{0} - {1}", a.Vname, a.Count);
}

If you want to return string splited by comma, try this:
C#
string sMid = "23065";
var re1 = String.Join(",", DB.tblVeh
           .Where(v=>v.MID.Equals(sMid) && v.Name != string.Empty)
           .GroupBy(v=>v.Name)
           .Select(g=> new
               {
                   a = String.Format("[{0},{1}]", g.Key.Name, g.Count())
               }));

Above code returns:
[d1,2],[e3,5],[g2,8]
 
Share this answer
 
v2
Comments
super_user 9-Jun-16 2:54am    
in foreach loop?
Maciej Los 9-Jun-16 4:11am    
Could you be more specific and provide more detais about your issue?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900