ToArray、ToList、ToDictionary、OfType

#region using
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Text;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.Collections;
#endregion


public  partial  class  _Default : System.Web.UI.Page 
{
    
protected void Page_Load(object sender, EventArgs e)
    
{
        
用ToArray()将查询结果转化为数组 

        
#region 用ToList()将查询结果转化为List集合
        Response.Write(
"<hr>用ToList()将查询结果转化为List集合<br>");
        var students1 
= from student in GetStudents()
                       where student.Age
>21
                       orderby student.Age
                       select student.Name;
        var nameArray1 
= students1.ToList();
        nameArray1.Add(
"newlist");
        
foreach (var name in nameArray1)
        
{
            Response.Write(
string.Format("<span class='result'>{0}</span>", name));
        }

        
#endregion
 

        
#region 用ToDictionary()将查询结果转化为Dictionary
        Response.Write(
"<hr>用ToDictionary()将查询结果转化为Dictionary<br>");
        var studentDict 
= GetStudents().ToDictionary(student => student.Name);
        var Y 
= studentDict["YOUNG"];
        Response.Write(
string.Format("<span class='result'>YOUNG:{0},{1},{2}</span>", Y.Name, Y.Age, Y.Language));
        
#endregion
 

        
#region 用OfType过滤查询结果中的类型
        Response.Write(
"<hr>用OfType过滤查询结果中的类型<br>");
        
object[] objects = 1"love",GetStudents()[1], 2.1null, GetStudents()[3],"young"};
        var students2 
= objects.OfType<Student>();
        
foreach (var student in students2)
        
{
            Response.Write(
string.Format("<span class='result'>{0}</span>", student.Name));
        }

        
#endregion

    }


    
#region 构造一个学生集合体
    
private List<Student> GetStudents()
    
{
        List
<Student> students = new List<Student> 
             
new Student{ Name="YOUNG", Age=25, Language="Chinese"},
             
new Student{ Name="JESSIE", Age=21, Language="Scotland"},
             
new Student{ Name="KELLY", Age=18, Language="English"},
             
new Student{ Name="JUNE", Age=20, Language="English"},
             
new Student{ Name="ADRIAN", Age=22, Language="Italy"},
             
new Student{ Name="BRUCE", Age=17, Language="Scotland"},
             
new Student{ Name="BRANT", Age=30, Language="Germany"},
             
new Student{ Name="BEN", Age=25, Language="Chinese"}
        }
;
        
return students;
    }

    
#endregion

}


学生类

显示结果
ToArray、ToList、ToDictionary、OfType 

你可能感兴趣的:(toArray)