linq 的用法小记-匿名类

这个代码里面用到了匿名类。
匿名类的用法, 感觉有点像JS里面的JSON了。但事实上,还是有区别的。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace LinqDemo
{
    
public partial class Form1 : Form
    
{
        
public Form1()
        
{
            InitializeComponent();
        }


        
private void btForeach_Click(object sender, EventArgs e)
        
{
            List
<Account> listAccount = CreateList();

            var accounts 
= from account in listAccount
                           orderby account.UserName
                           select 
new { account.UserName, account.Pwd };

            
foreach (var account in accounts)
            
{
                lvForeach.Items.Add(account.Pwd.ToString());
            }

        }

        List
<Account> CreateList()
        
{
            List
<Account> list = new List<Account>();
            list.Add(
new Account("account4""Paccount4"));
            list.Add(
new Account("account1""Paccount1"));
            list.Add(
new Account("account2""Paccount2"));
            list.Add(
new Account("account3""Paccount3"));
            
return list;
        }

    }


    
public class Account
    
{
        
public string UserName
        
{
            
get;
            
set;
        }

        
public string Pwd
        
{
            
get;
            
set;
        }

        
public Account(string username,string pwd)
        
{
            
this.UserName = username;
            
this.Pwd = pwd;
        }

    }

}


posted on 2008-07-07 18:06  房客  阅读(745)  评论(0编辑  收藏  举报

导航