Matching values in a list collection and values in the DataTable row in C#

670 Views Asked by At

Good day Coders

I would like to know is there a way of matching values from a list collection to a data table row. Currently I have this, that doesn't work. Ref_Number is the list collection and dtRefNum is the DataTable row

 int count = Ref_Number.Count > dtRefNum.Rows.Count ? dtRefNum.Rows.Count : Ref_Number.Count;
 for (int i = 0; i < count; i++ )
 {
     if (Ref_Number[i].ToString().Trim().Contains(dtRefNum.Rows[i].ToString().Trim()))
      {
           var refnum = Ref_Number[i].ToString().Trim();
           var fsdfsdf = dtRefNum.ToString().Trim();
      }
      else if (Ref_Number[i].ToString().Trim() == dtRefNum.Rows[i].ToString().Trim())
      {

      }
2

There are 2 best solutions below

3
Jimbot On

You may want to try this,

//assumming Ref_Number is List<string>
    for (int i = 0; i < dtRefNum.Rows.Count; i++ )
     {
         if ((Ref_Number.Where(rn => rn.ToLower().Trim() == dtRefNum.Rows[i].ToString().ToLower().Trim()).Count()) > 0)
          {
               var refnum = Ref_Number[i].ToString().Trim();
               var fsdfsdf = dtRefNum.ToString().Trim();
          }
    }
0
Javier Jimenez Matilla On

I don't know what are you looking for but if you have more rows in the list than in the table, it's ok? I don't know.

If you want to use linq, but I think it's the same:

int i=0;
Ref_Number.foreach(oh => 
    {
        if (oh[i].ToString().Trim() = dtrefnum[i].ToString().Trim(); //or use contains whateveryouwant
            ...
    }