Question

I have a class:

public class Cards
{ 
   private string _type= string.Empty;
   private string _name= string.Empty;

   public string Type
   {
       get { return _type; }
       set { _type= value; }
    }

public string Name
{
    get { return _name; }
    set { _name= value; }
} 
}

I have an object of this class.

public List<Cards> CardTypes = new List<Cards>();

Values in list Cards is:

Name     Type
==============
Visa          Vi

Master        MA

Discover      DI

I have a DataTable cardTable with following columns:

Name,Value,CCvName

+---+------------+-------------+
|Val|  Name      |    CCV      |
+---+------------+-------------+
| 1 | Visa       |   441       |
| 2 | Master     |   121       |
| 3 | Amex       |   111       |
| 4 | Diners     |   222       |
+---+------------+-------------+

Both List and DataTable have unique values. I want to filter the data from datatable on the basis of Name field in List (delete other records from cardTable). All the values are of string type.

The resulting cardTable should be:

+---+------------+-------------+
|Val|  Name      |    CCV      |
+---+------------+-------------+
| 1 | Visa       |   441       |
| 2 | Master     |   121       |
+---+------------+-------------+

Thanks in advance.

Was it helpful?

Solution

An easy way is to use RowFilter (either on a new DataView or the default DataView of the DataTable).

Given cardTable and cardTypes:

var view = new DataView(cardTable)
{
    // create filter: [Name] IN ('Visa','Master','Discover')
    RowFilter = String.Format("[Name] IN ({0})", String.Join(",", cardTypes.Select(t => "'" + t.Name + "'")))
};

view now contains the rows you're looking for.


If you really want a LINQ solution, you could use a simple Join:

cardTable = cardTable.AsEnumerable()
                     .Join(cardTypes,
                           i => i.Field<string>("Name"),
                           o => o.Name,
                           (i, o) => i)
                      .CopyToDataTable();

OTHER TIPS

You can write LINQ join query returning rows without corresponding card type in list:

var rowsToDelete = from r in cardTable.AsEnumerable()
                   join c in CardTypes 
                        on r.Field<string>("Name") equals c.Name into g
                   where !g.Any()
                   select r;

And then just remove those rows:

foreach(var row in rowsToDelete)
    cardTable.Rows.Remove(row);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top