Click here to Skip to main content
15,881,803 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to Retrieve only First two characetrs from DataTable's Column Which are Unique in C#

I Can Take Out Unique Records So Currently I Need only Two Characters

e.g.
My DataTable is

C#
SrNo  VrNo
 1    BR123
 2    BP321
 3    BR111

So I Want Result as
C#
VrNo
BR
BP
BR


And After That I Can take out Unique

Please Help Me How Can I Do This...?
Posted
Updated 30-Jul-14 23:53pm
v2

try with Substring(0,2) this.. :)


C#
string strData=dt.Rows[0]["VrNo"].toString();
string YourOutput=strData.Substring(0,2);
 
Share this answer
 
Comments
prashantttt 31-Jul-14 6:20am    
This will increase processing time that's why I'm looking for any other way
like the way in sql server select left()
Nirav Prabtani 31-Jul-14 6:24am    
I agree with you but you have tag c# , otherwise i'll suggest you same if you tah it SQL instaed
CHill60 31-Jul-14 6:29am    
Answered as per the question and tags! Giving a 4 rather than a 5 because it could have been done in a single line - I can be picky like that :-). Changed my mind - giving it a 5 because splitting the lines highlights the bit that does the substring
Nirav Prabtani 31-Jul-14 6:43am    
Thanks .. :)
CHill60 31-Jul-14 6:25am    
This is exactly the same as sql server left() ... how are you populating your datatable?
Further to solution 1, you haven't mentioned how you are taking out the unique records.
If you use a HashSet you can do both the truncation to 2 characters and the "uniqueness" at the same time.
(Nice example here[^] but the adverts are annoying)
Essentially if you try to add a duplicate entry into the Set no exception is raised but the duplicate is not added. It's also quite quick!

For example
C#
HashSet<string> hs = new HashSet<string>();
foreach (DataRow row in dt.Rows)
    hs.Add(row["VrNo"].ToString().Substring(0,2));

Using the HashSet is the same as going through your datatable e.g.
C#
foreach (string s in hs)
    // do something with s
 
Share this answer
 
Try this:
C#
var res = dt.AsEnumerable().Select(s => s.Field<string>("VrNo")).Distinct().Select(s => s.Substring(0, 2));
    foreach (var r in res)
        Console.WriteLine(r);</string>



--Amy
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900