someone
someone

Reputation: 575

generating list of lists with linq

i have a query which its result is as follow:

----------------------------
sid    name    count
----------------------------
1021   o        1
1021   t        5
1022   t        10
1023   h        14

my desired result should be list which first element is sid(which is unique) and second element should be a list of name and count

something like this:

[1021, [(o,1), (t,5)]]; [1022, (t,10)]

i have no idea what to do, maybe i can use dictionary but i cant distinguish unique sids. can some one give me a hint? tnx in advanced

Upvotes: 0

Views: 107

Answers (1)

Enigmativity
Enigmativity

Reputation: 117175

You could do this:

var source = new []
{
    new { sid = 1021, name = "o", count = 1, },
    new { sid = 1021, name = "t", count = 5, },
    new { sid = 1022, name = "t", count = 10, },
    new { sid = 1023, name = "h", count = 14, },
};

var query =
    from x in source
    group new { x.name, x.count } by x.sid;

That gives me this:

query

If you specifically wanted that textual output then this would work:

var query =
    String.Join("; ",
        from x in source
        group new { x.name, x.count } by x.sid into gxs
        select String.Format("[{0}, [{1}]]", gxs.Key, String.Join(", ",
            gxs.Select(gx => String.Format("({0},{1})", gx.name, gx.count)))));

Then I get:

[1021, [(o,1), (t,5)]]; [1022, [(t,10)]]; [1023, [(h,14)]]

Upvotes: 3

Related Questions