How to filter Data table - c#

I want to filter data table based on some condition .
I have a data table like that
Tabel A
MobileNo Email
9999999999 test#test1.com
8888888888 test#test2.com
9999999999 test#test5.com
7777777777 test#test6.com
I want to get distinct value based on mobile also I need data that not exits in distinct table but table A have
Like
Distinct Table Ignore Table
MobileNo Email MobileNo Email
9999999999 test#test1.com 9999999999 test#test5.com
8888888888 test#test2.com
7777777777 test#test6.com
I have also tried googling but that are not very much understandable.
Thanks in Advance

You can use the select method on DataTable
Dim dtFiltered As New DataTable()
dtFiltered = dtAllData.DefaultView.ToTable(True, "MobileNo")
dtAllData is the DataTable containing all records
dtFiltered contains only Distinct Records
For more details check MSDN article
UPDATE based on your comment
In that case you need to use except as in
datatable-comparison-using-linq-except-intersect-union
From all records extract distinct records to second DataTable and then use Except to compare the first and second DataTable

Thanks for all your help
Finally I got the solution
Dim ValidData = (From row In tbValid.AsEnumerable()
Let Mobile = row.Field(Of String)("Mobile")
Group row By Mobile Into DupMobile = Group
Select DupMobile.First).ToArray
Dim Ignoredata = tbValid.AsEnumerable().Except(ValidData.AsEnumerable(), DataRowComparer.Default).ToArray

From your example all you have done is order your mobile no. in desending order which means you could then create a SQL to say something like: ORDER BY MobileNo DESC at the end of the statement. At least it will display the same way
Or are you meaning:
Dim dv As DataView = New DataView(DataTable.DataView)
dv.RowFilter = "%" &...

Related

In Data table first column displaying with tablename.columnname in c#

When i am running query in data base and fill data table with load method first column name coming with table name.column name(Employee.Name,sal,location) rest of the column name coming only column names present in the database.Why table name appending first column name while displaying in data table structure please help me in this regards.
DataTable table = new DataTable();
try
{
using (IDbCommand DbCommand = dbConnection.CreateCommand())
{
DbCommand.CommandText = query;
IDataReader reader = DbCommand.ExecuteReader();
table.Load(reader);
}
}
Sample query Select Employee.Numnber, Employee.salary, Employee.city,dept.deptId from Employee inner join dept where deptiId=EmployeeDeptId
The actual query is :
Select
AP_LINE.LINE_NO, AP_LINE.PRODUCT, AP_LINE.QTY, AP_LINE.REQUESTED_DATE,
AP_LINE.LIST_PRICE, AP_LINE.CONS_NET_MULT,AP_LINE.NETADDERS,
AP_LINE.CONS_NET_PRICE, AP_LINE.Details,TDP_JSP.ID, TDP_JSP.LINE_NO,
TDP_JSP_AppInfo.Id
From AP_LINE, CONFIG, TDP_JSP
inner join TDP_JSP_AppInfo on TDP_JSP.ID= TDP_JSP_AppInfo.ID
where AP_LINE.LINE_NO = TDP_JSP.LINE_NO ;
Out put in data table as coming below
Ap_Line.Line_No,Product,QTY,Requested Date...
There are two LINE_NO columns in the query, AP_LINE.LINE_NO and TDP_JSP.LINE_NO. Columns must have unique names, so DataTable.Load used the two-part name wherever needed. It that wasn't possible it would start appending indexes or even generate names like Column0, Column1 etc.
In this case though, one of those columns isn't needed. The two tables are join those columns. WHERE AP_LINE.LINE_NO = TDP_JSP.LINE_NO is the old-style, frowned-upon join syntax. Those two columns will always have the same data so one of them can be removed.

get the datatable with distinct rows in C#

I have a datatable returned as a result of fetching data from a spreadsheet. I need to display the resultset only with the distinct rows depends up on only a column.
For example I have a datatable with columns
id | name | age | email
Then if more than one record with the same id is listed it should omitted. I tried
dt = dt.DefaultView.ToTable(true)
but it returns the distinct records with respect to all columns. I need the distinct records only based on the id.
Can anyone help me on this?
You can use GroupBy :-
DataTable result = dt.AsEnumerable()
.GroupBy(x => x.Field<int>("Id"))
.Select(x => x.First()).CopyToDataTable();
Please note, in case of a matching Id, I am taking the first record and ignoring the rest.
You need to mention the column name on which the ToTable operation will execute to select distinct values.
Please find below the code section
DataView view = new DataView(table);
DataTable distinctValues = view.ToTable(true, "id");

Show details of current user in different table from database

In my database, there are two tables. Both have a username column. Table A is stores user information, and Table B is stores users' reservations. In my page, there will be a drop down menu that will retrieve BookingIDs for the currently logged in user. How should they be retrieved?
To help you understand, this should give you an idea of what I mean.
User X login,
If User X(Table A) = User X(Table B)
Then dropdown1 shows BookingID of User X from Table B.
I am sorry I don't provide any code because I really don't have any idea how to do it. Any answers are welcome. Thanks in advance.
This will list all BookingIDs of users that are in both tables:
select b.BookingID
from tableA a
inner join tableB b on a.username = b.username
Using SQL
SELECT
//TABLE_A.required_cols
//TABLE_B.required_cols
FROM
TABLE_A
JOIN TABLE_B ON TABLE_A.USER_ID = TABLE_B.USER_ID
Note:: Here I've assumed that both tables have a column called USER_ID that match for the same user, say X
Create a data table and then populate it create the table as follows:
Private Function CreateDataSource() As DataTable
'creates the columns for the datatable
Dim dt As New DataTable 'create new datatable
'add appropriate columns to the table
Dim colImage As New DataColumn("Field1", GetType(Boolean))
colImage.DefaultValue = bShowExtraInfo
dt.Columns.Add(colImage)
dt.Columns.Add("Field2", GetType(String))
Return dt 'return the table
End Function
and then use it in your code like so:
Dim dt As DataTable = CreateDataSource() 'create the data table
Dim dr As DataRow
For Each x In y 'cycle through x and add to table
dr("Field1") = tableAvalue
dr("Field2") = tableBvalue
dt.Rows.Add(dr)
End If
Next
gvEverything.DataSource = dt
gvEverything.DataBind()

How to get unique records of specific columns of data table

I have a DataTable imported from Excel file.
Data i need is only unique from specific columns of the DataTable.
The unique data i meant is like when a command DISTINCT is used in SQL Select Query.
I want to get the list of the unique data from the DataTable Column and put them into List
I think LinQ can be used for this matter but i'm not so familiar with it.
I was thinking of code like this below
var data is from MyDataTable
where MyDataTable.ColumnName = "SpecificColumn"
select MyDataTable["SpecificColumn"]).UniqueData;
List<string> MyUniqueData = new List<string>();
foreach(object obj in data)
{
if(MyUniqueData.NotContain(obj))
MyUniqueData.add(obj);
}
I hope someone can drop off some knowledge to me.
var unique = data.Distinct().ToList();
What you're looking for is .Distinct(). See MSDN documentation here. You can specify your own comparer if you need something specific and it will return only unique records.
If you have a Datatable or DataView, inorder to get unique records from a column, you have to write this.
this would be simple.
DataTable dtNew = dt.DefaultView.ToTable(true, "ColName"); // for Datatable
DataTable dtnew= dv.ToTable(true, "ColName"); // for DataView

c# DataTable.Select: problem with '-' character

I have a problem in a C# project. I am using the Select method with a DataTable object.
If I put a '-' in the search string I select nothing.
So here is a code sample of what I have:
DataTable table;
DataRow[] rows = table.Select("[Radio Name] LIKE '*Lounge-MP3-96*'");
But there is a column with:
Radio Name = 1.FM - The Chillout Lounge-MP3-96
Have I to escape characters? How?
I've just tried
DataTable table;
DataRow[] rows = table.Select("[Radio Name] LIKE '*Lounge*'");
It works!
So it seems really related to the "-"....
I don't think it's the "-". I thought wildcards needed to be percent symbols for the datatable select (it mimics SQL): "%"?
Try this:
DataTable table = GetTableFromSomewhere();
DataRow[] rows = table.Select("[Radio Name] LIKE '%Lounge-MP3-96%'");
Also, your example doesn't populate the table with anything in the first place so it wouldn't work - I'm assuming you do populate your table somehow.

Categories