RRZ Europe
RRZ Europe

Reputation: 954

Linq: select grouped lists

I am beginning to use Linq, and think it is the correct way to solve my problem, but do not know how to tackle the following :

I have a dataset which is filled from a DB Table. it contains data like the following

CAT  VALUE
c1    NULL or ""
c2    a
c2    b
c3    x
c4    y
c4    z

as a result, I want something like a dictionary with cat as key and the grouped values as a list

giving:
_pseudoFunction_.getByKey(c2) => List with a,b 
_pseudoFunction_.getByKey(c1) => nothing

how can I reach this with linq or is there even a better way?

Upvotes: 3

Views: 163

Answers (3)

Ahmad Mageed
Ahmad Mageed

Reputation: 96557

A lookup fits nicely. You can use the Enumerable.ToLookup method as follows:

var query = table.ToLookup(o => o.CAT, o => o.Value);

// specific key: c2
foreach (var item in query["c2"])
{
    Console.WriteLine(item);
}

// all items
foreach (var item in query)
{
    Console.WriteLine("Key:" + item.Key);
    foreach (var value in item)
    {
        Console.WriteLine(value);
    }
}

To check for null or an empty string you can modify the approach in this way:

if (query["c1"].Any(o => !String.IsNullOrEmpty(o)))
{    
    foreach (var item in query["c1"])
    {
        Console.WriteLine(item);
    }
}
else
{
    Console.WriteLine("No valid results for c1");
}

Upvotes: 1

Johny Skovdal
Johny Skovdal

Reputation: 2104

var resultAsDictionary = myDataSet.Rows.Cast<DataRow>().ToDictionary(e => e["CAT"].ToString(), e => e["VALUE"].ToString())
Is that what you wanted? I'm only guessing your datamodel though, so I might have misunderstood something.

Upvotes: 0

Bala R
Bala R

Reputation: 109037

List<?> getByKey(TypeOfCAT input)
{
    return context.yourTable.Where(i => i.CAT == input).Select(i=>i.Value).ToList();
}

should work if you fill out ? and TypeOfCAT

Upvotes: 1

Related Questions