Convert part of C# datacolumn to linear string

167 Views Asked by At

I am having below datatable,

Column1 Column2
one This is one
two This is two
three This is three
four This is four

my flow will receive parameter as "one", "two", "three" or "four" and based on this parameter, output string should be like below,

If "one" is parameter then output string -> This is one
If "two" is parameter then output string -> This is one, This is two
If "four" is parameter then output string -> This is one, This is two, This is three, This is four

Above can be achieved using loop but wanted to checked if there can be a better way of doing it(using linq?).

For simplicity I updated datatable with simple strings(one, two..etc). However in actual case, data table will have random strings. My requirement would be like below.

"If the passed parameter is in nth row of column 1, then result would be column2(row 1) +","+ column2(row 2)+"," +......+","+column2(row n)."

Thanks!

2

There are 2 best solutions below

0
Maciej Los On BEST ANSWER

Your question is not clear, but...

Assuming that you've got datatable with 2 columns type of string, then you need to find index of row with parameter equals to Column1 and return concatenated string from Column2.

string parameter = "four";

DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[]
    {
        new DataColumn("Column1", typeof(string)),
        new DataColumn("Column2", typeof(string))
    });
dt.Rows.Add(new object[]{"one", "string related to 'one'"});
dt.Rows.Add(new object[]{"two", "string related to 'two'"});
dt.Rows.Add(new object[]{"three", "string related to 'three'"});
dt.Rows.Add(new object[]{"four", "string related to 'four'"});

DataRow row = dt.Select($"Column1 = '{parameter}'").First();
if(row==null) return;
int pos = dt.Rows.IndexOf(row);
string result = string.Join("; ", dt.AsEnumerable()
    .TakeWhile((x, y) => y<=pos)
    .Select(x =>x.Field<string>("Column2")));
    
Console.WriteLine(result);
2
Asad Iftikhar On

In Grid View where you are checking

this is One

You can Simple do This is and then print One two three from DB by counting Length

Hope this is the best technique and easy technique