LINQ - Get list of value starting with specific characters

Hi,
I have a datatable (dt_InputFile) with 2 columns “A” and “B”
A | B
1234 | 1234890
1234 | 1234891
1234 | 1234892
7789 | 7789600
7789 | 7789601

If I want the distinct values for column A, I can get it with an assign:
list_output = (From r In dt_InputFile.AsEnumerable() Select r.Field(Of String)(“A”)).Distinct.ToList
=> The output is stored in a list of string with values 1234 and 7789

If I want the same result but with a Datatable as output I write an assign:
dt_output = dt_InputFile.DefaultView.ToTable(True,“A”)

Now, I would like to store for each distinct value from Col A, the corresponding values from column B.
Ex: For 1234=> 1234890, 1234891, 1234892 and for 7789=> 7789600, 7789600
I would like the output as a list of strings (or as a DT for each case).

As you can see, the value from column B starts with the value of column A.
If I try with StartWith… the output is a boolean, so it’s not working.
I don’t know if it’s better to get the info with a “start with” or to simply get the value corresponding to distinct col A.

Could you help me to get the Linq Syntax please?

Hi,

How about using Dictionary<String, List<String>> as the following expression?

dict = dt.AsEnumerable.GroupBy(Function(r) r("A").ToString).ToDictionary(Function(g) g.Key,Function(g) g.Select(Function(r) r("B").ToString).ToList)

Regards,

1 Like

it is a group by case

give try at:

Assign activity:
dtResult = dt_InputFile.Clone

Assign Activity:
dtResult =
(From d in dt_InputFile.AsEnumerable
Group d by k=d(“A”).toString.Trim into grp=Group
Let bc = String.Join(“,”, grp.Select(Function (x) x(“B”).toString.Trim))
Let ra = new Object() {k,bc}
Select r = dtResult.Rows.Add(ra)).CopyToDataTable

Another option could be to get a dictionary where key is A and Value the B groupmembers as list

dictLK | Dictionary (of String, List(ofString)) =
(From d in dt_InputFile.AsEnumerable
Group d by k=d(“A”).toString.Trim into grp=Group
Let bl = grp.Select(Function (x) x(“B”).toString.Trim).toList
Select t = Tuple.Create(k, bl)).ToDictionary(Function (t) t.Item1, Function(t) t.Item2)

1 Like

Thank you very much, all the solutions are ok!

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.