从DataTable获取数据 [英] Fetch Data From DataTable
本文介绍了从DataTable获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想只检索DataTable列中的前两个characetrs在C#中是唯一的#
我可以取出唯一记录所以目前我只需要两个字符
例如
我的DataTable是
SrNo VrNo
1 BR123
2 BP321
3 BR111
所以我希望结果为
VrNo
BR
BP
BR
之后我可以拿出独特的
请帮帮我我该怎么做...?
解决方案
尝试子串(0,2)
这个.. :)
string strData = dt.Rows [ 0 ] [ VrNo跨度>]的toString();
string YourOutput = strData.Substring( 0 , 2 );
除解决方案1外,您还没有提到如何取出唯一记录。
如果使用HashSet,你可以同时截断到2个字符和唯一性。
(很好的例子 [ ^ ]但广告很烦人)
基本上如果你尝试在Set中添加一个重复的条目,则不会引发异常,但副本是没有添加。它也很快!
例如HashSet< string> hs = new HashSet< string>();
foreach (DataRow row in dt.Rows)
hs.Add(row [ VrNo]。ToString()。Substring( 0 , 2 ));
使用HashSet与通过数据表相同例如foreach ( string s in hs)
// 用s $ p做点什么$ p>
试试这个:
var res = dt.AsEnumerable()。选择(s = > s.Field< string>( VrNo))。Distinct()。选择(s = > s.Substring( 0 , 2 ));
foreach ( var r in res)
Console.WriteLine(r); < / string >
- Amy
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
SrNo VrNo
1 BR123
2 BP321
3 BR111
So I Want Result as
VrNo
BR
BP
BR
And After That I Can take out Unique
Please Help Me How Can I Do This...?
解决方案
try withSubstring(0,2)
this.. :)
string strData=dt.Rows[0]["VrNo"].toString(); string YourOutput=strData.Substring(0,2);
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 exampleHashSet<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.foreach (string s in hs) // do something with s
Try this:
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
这篇关于从DataTable获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文