2

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.

1

2 Answers 2

5

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();
1
  • and use System.Data.DataSetExtensions.dll Refrence
    – Amir Reza
    Feb 5, 2020 at 7:08
3

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"];
3
  • ok, how to retrieve the values separately in string [] for us and uk separate? May 24, 2014 at 10:34
  • @user2979719 Iterate over the dictionary to print the values (see the edit). May 24, 2014 at 10:38
  • @user2979719 Why "effort"? You mean you couldn't make it work? May 24, 2014 at 10:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.