user2979719
user2979719

Reputation: 59

Where clause in C# linq to datatable

I have two columns with Col1 and col2 in data table like below:

enter image description here

note:

col1 contains only us or uk, no other values

Now my requirement is to separate the values based on us and uk.

Like below get all the values corresponding to us and uk seperately.

Earlier I have done this with linq code. At that time my requirement is a simple one,

just get all the records in col2:

string[] data = dt.AsEnumerable()
  .Select(s => s.Field<string>("col2"))
  .ToArray<string>();

now in the new requirement I need them separately based on us and uk.

Upvotes: 2

Views: 33973

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726509

When you need to separate your items based on a value of some column, you use GroupBy, like this:

var groups = dt.AsEnumerable().GroupBy(s => s.Field<string>("col1"));

Once you have your groups, you can iterate them, or "materialize" them in a Dictionary<string,string[]>, like this:

var byCol1 = groups.ToDictionary(g => g.Key, g => g.Select(s => s.Field<string>("col2")).ToArray());

You can output the numbers for each key like this:

foreach (var p in byCol1) {
    Console.WriteLine("{0} : {1}", p.Key, string.Join(", ", p.Value));
}

or get the numbers for a specific key like this:

string[] items = byCol1["us"];

Upvotes: 3

SoftwareFactor
SoftwareFactor

Reputation: 8588

To get a list of all col2 values where col1 is equal to "us", you could use code like this:

string[] data = dt.AsEnumerable().Where(s => s.Field("col1") == "us").Select(s => s.Field("col2")).ToArray();

Upvotes: 6

Related Questions