DOTNET最近的一些技巧

List和string之间的互相转换

我们在开发中经常会用List<string>来保存一组字符串,比如下面这段代码:

List<string> studentNames = new List<string>();

studentNames.Add(
"John");
studentNames.Add(
"Mary");
studentNames.Add(
"Rose");


可是有时候,我们要从中获取一个字符串,字符串的内容就是集合中的内容,但是要用逗号隔开,下面的办法可以实现:

string.Join("", studentNames.ToArray())


 上面这条语句,返回的结果应该是下面这个样子:

John, Mary, Rose


下面让我们来做个反向工程,从string转换成List<string>

string result = string.Join("", studentNames.ToArray());

List
<string> newStudentNames = new List<string>(result.Split(new string[] { "" }, StringSplitOptions.RemoveEmptyEntries));

foreach (string s in newStudentNames)
{
    System.Diagnostics.Debug.WriteLine(s);
}


输出结果如下:

John
Mary
Rose

 

 

原来DataTable的Distinct竟如此简单!

有时我们需要从DataTable中抽取Distinct数据,以前总是以对DataTable进行foreach之类纯手工方式获取。

近来发现DataView可以帮我们直接获取Distinct数据,汗一个!

DataTable dataTable;

DataView dataView = dataTable.DefaultView;

DataTable dataTableDistinct = dataView.ToTable(true,"FieldName1","FieldName2","...");//注:其中ToTable()的第一个参数为是否DISTINCT

 

 

DataTable分页

/// <summary>
 2         /// 对DataTable进行分页,起始页为1
 3         /// </summary>
 4         /// <param name="dt"></param>
 5         /// <param name="PageIndex"></param>
 6         /// <param name="PageSize"></param>
 7         /// <returns></returns>
 8        public static DataTable GetPagedTable(DataTable dt, int PageIndex, int PageSize)
 9         {
10             if (PageIndex == 0)
11                 return dt;
12             DataTable newdt = dt.Copy();
13             newdt.Clear();
14 
15             int rowbegin = (PageIndex - 1* PageSize;
16             int rowend = PageIndex * PageSize;
17 
18             if (rowbegin >= dt.Rows.Count)
19                 return newdt;
20 
21             if (rowend > dt.Rows.Count)
22                 rowend = dt.Rows.Count;
23             for (int i = rowbegin; i <= rowend - 1; i++)
24             {
25                 DataRow newdr = newdt.NewRow();
26                 DataRow dr = dt.Rows[i];
27                 foreach (DataColumn column in dt.Columns)
28                 {
29                     newdr[column.ColumnName] = dr[column.ColumnName];
30                 }
31                 newdt.Rows.Add(newdr);
32             }
33 
34             return newdt;
35         }

 

 

 

 NET中Web Service和Web Form获得客户端IP的方法 收藏
在.NET中,WebService和WebForm页面,使用了不同的获得客户IP方法。
        注:以下方法在.NET2.0上测试通过。

Web Service使用(通过HttpContext对象调用Request对象):

HttpContext.Current.Request.UserHostAddress

HttpContext.Current.Request.ServerVariables.GetValues("REMOTE_ADDR")[0]

Web Form使用(可直接使用Request对象):

Request.ServerVariables.GetValues("REMOTE_ADDR")[0]

HttpContext.Current.Request.UserHostAddress

 

posted on 2010-11-04 21:58  云帅工作室  阅读(421)  评论(0)    收藏  举报

导航