简体   繁体   中英

Linq Datatable subset using group by and having count >1

Need some help with Linq.

I have a Datatable which looks like the following I just have the W_text with me to search

Using the above datatable, I would like to extract the subset of rows having the following result

The key to search is "First Employee"

So as you can see, I want to get a subset of those rows which have W_Text values as "First" and "Employee" but having the same l_id.

In DB terms, this would be a Select * from Table 1 where W_Text in ('First','Employee') group by l_id having l_id > 1 (or something like this).

How do i achieve this in C# using a datatable?

I tried playing around with the following code, but this gives me the whole datatable with other rows as well. I am not sure how to use group by and having clause. I would appeciate if someone can help me in this regard.

var results = from myRow in dtResult.AsEnumerable()
              where myRow.Field<string>("W_Text") == "First" ||
                    myRow.Field<string>("W_Text") == "Employee"
              select myRow;

dtCopy = results.CopyToDataTable();

Hi you can use like this as shown

var results = (from myRow in dtResult.AsEnumerable()
              where myRow.Field<string>("W_Text") == "First" ||
              myRow.Field<string>("W_Text") == "Employee"
              select myRow ).ToLookup(item => item.Field<string>("l_id"));

OR

var results = (from myRow in dtResult.AsEnumerable()
               where myRow.Field<string>("W_Text") == "First" ||
               myRow.Field<string>("W_Text") == "Employee"
               select myRow).GroupBy(item => item.Field<string>("l_id")).ToList();

Check the following:

      List<string> wTextFilter = new List<string>();
        wTextFilter.Add("First");
        wTextFilter.Add("Employee");

        // Get all Id's that satisfy all conditions:            
        List<int> results = dt.AsEnumerable()
            // Get all Id's:
            .Select(dataRow => dataRow.Field<int>("l_id"))
            // Filter the Id's : 
            .Where(id =>
                // the Id should be greater than one.
                    id > 1   &&
                    // check if all W_Text entries has a record in the datatable with the same Id.
                    wTextFilter.All(W_Text => dt.AsEnumerable().Any(dataRow => dataRow.Field<string>("W_Text") == W_Text && dataRow.Field<int>("l_id") == id)))
                    .Distinct().ToList();

        // Get all datatable rows filtered by the list of Id's.
        DataTable dtCopy = dt.AsEnumerable().Where(dataRow => results.Contains((dataRow.Field<int>("l_id")))).CopyToDataTable();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM