user1366062
user1366062

Reputation: 303

C# LINQ filtering

I have this piece of code

            var tblGrouped = dtCSV.AsEnumerable()
                .GroupBy(r => new
                {
                    product_id   = r.Field<String>("product_id"),
                    owner_org_id = r.Field<String>("owner_org_id"),
                });

But I want to add an additional column to filter by. Basically if course_type_id = 1 for example. dtCSV is the source where the course_type_id is populated. I tried the following but it didn't work:

            var tblGrouped = dtCSV.AsEnumerable()
                .GroupBy(r => new
                {
                    product_id   = r.Field<String>("product_id"),
                    owner_org_id = r.Field<String>("owner_org_id"),
                    course_type_id = "1",
                });

Upvotes: 1

Views: 1135

Answers (3)

Ry-
Ry-

Reputation: 225203

You'll want to add the condition first. You can do that using .Where:

var tblGrouped = dtCSV.AsEnumerable()
    .Where(r => r.Field<String>("course_type_id") == "1")
    .GroupBy(r => new
    {
        product_id   = r.Field<String>("product_id"),
        owner_org_id = r.Field<String>("owner_org_id"),
        course_type_id = "1"
    });

Upvotes: 2

AD.Net
AD.Net

Reputation: 13409

To filter by use Where syntax Ex. .Where(a=>a.Field<String>("course_type_id") == "1")

Upvotes: 2

user7116
user7116

Reputation: 64138

If I understand your requirement correctly, you want to group rows which have a course_type_id of 1?

var tblGrouped = dtCSV.AsEnumerable()
    .Where(r => r.Field<String>("course_type_id") == "1")
    .GroupBy(r => new
        {
            product_id   = r.Field<String>("product_id"),
            owner_org_id = r.Field<String>("owner_org_id"),
        });

Upvotes: 6

Related Questions