Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i do this in Linq?

Tags:

json

.net

linq

i've got an IList<Foo> and I'm trying to serialize it as Json without the field names included in the result. As such, i'm trying to create an anonymous object, which i pass to the Json serialization method.

Foo is defined as (pseudo code):-

public class Foo
{
    public int X;
    public int Y;
}

When i return this as Json ...

return Json(foos);

the result is like

... [{"X":1,"Y":2},{"X":3,"Y":4}...]

I don't want the X and Y to be there. So i'm after..

... [{1,2},{3,4}...]

So i was trying to do the following (which doesn't work)

(from p in foos
 select new p.X + "," + p.Y).ToArray()

or

(from p in foos
 select new string(p.X+ "," + p.Y)).ToArray()

but to no avail (doesn't compile).

Can anyone help, please?

like image 410
Pure.Krome Avatar asked Jan 29 '26 01:01

Pure.Krome


2 Answers

(from p in foos
 select String.Format("{{{0}, {1}}}", p.X, p.Y)).ToArray()
like image 163
Thomas Levesque Avatar answered Jan 31 '26 15:01

Thomas Levesque


foos.Select(p=>p.X + "," + p.Y)

Or if you perfer Linq Syntax:

(from p in foos
 select p.X + "," + p.Y).ToArray()
like image 31
treehouse Avatar answered Jan 31 '26 15:01

treehouse