委托,泛型List<>[Sort (),FindAll (),BinarySearch ()] ,泛型绑定下拉框

 

C# list使用方法

 

http://lulitianyu.blog.163.com/blog/static/913603020103505359480/
 

# List泛型集合

集合是OOP中的一个重要概念,C#中对集合的全面支持更是该语言的精华之一。

    为什么要用泛型集合?

    在C# 2.0之前,主要可以通过两种方式实现集合:

    a.使用ArrayList

    直接将对象放入ArrayList,操作直观,但由于集合中的项是Object类型,因此每次使用都必须进行繁琐的类型转换。

    b.使用自定义集合类

    比较常见的做法是从CollectionBase抽象类继承一个自定义类,通过对IList对象进行封装实现强类型集合。这种方式要求为每种集合类型写一个相应的自定义类,工作量较大。泛型集合的出现较好的解决了上述问题,只需一行代码便能创建指定类型的集合。

    什么是泛型?

    泛型是C# 2.0中的新增元素(C++中称为模板),主要用于解决一系列类似的问题。这种机制允许将类名作为参数传递给泛型类型,并生成相应的对象。将泛型(包括 类、接口、方法、委托等)看作模板可能更好理解,模板中的变体部分将被作为参数传进来的类名称所代替,从而得到一个新的类型定义。泛型是一个比较大的话 题,在此不作详细解析,有兴趣者可以查阅相关资料。

 

 

    怎样创建泛型集合?

    主要利用System.Collections.Generic命名空间下面的List<T>泛型类创建集合,语法如下:

定义Person类如下:

   可以看到,泛型集合大大简化了集合的实现代码,通过它,可以轻松创建指定类型的集合。非但如此,泛型集合还提供了更加强大的功能,下面看看其中的排序及搜索。

List<T> ListOfT = new List<T>();

其中的"T"就是所要使用的类型,既可以是简单类型,如string、int,也可以是用户自定义类型。下面看一个具体例子。

 

class Person

{

    private string _name; //姓名

    private int _age; //年龄

    //创建Person对象

    public Person(string Name, int Age)

    {

        this._name= Name;

        this._age = Age;

    }

    //姓名

    public string Name

    {

        get { return _name; }

    }

    //年龄

    public int Age

    {

        get { return _age; }

    }

}

//创建Person对象

Person p1 = new Person("张三", 30);

Person p2 = new Person("李四", 20);

Person p3 = new Person("王五", 50);

//创建类型为Person的对象集合

List<Person> persons = new List<Person>();

//将Person对象放入集合

persons.Add(p1);

persons.Add(p2);

persons.Add(p3);

//输出第2个人的姓名

Console.Write(persons[1].Name);

    泛型集合的排序

    排序基于比较,要排序,首先要比较。比如有两个数1、2,要对他们排序,首先就要比较这两个数,根据比较结果来排序。如果要比较的是对象,情况就要复杂一 点,比如对Person对象进行比较,则既可以按姓名进行比较,也可以按年龄进行比较,这就需要确定比较规则。一个对象可以有多个比较规则,但只能有一个 默认规则,默认规则放在定义该对象的类中。默认比较规则在CompareTo方法中定义,该方法属于IComparable<T>泛型接口。 请看下面的代码:

class Person :IComparable<Person>

{

    //按年龄比较

    public int CompareTo(Person p)

    {

        return this.Age - p.Age;

    }

}

    CompareTo方法的参数为要与之进行比较的另一个同类型对象,返回值为int类型,如果返回值大于0,表示第一个对象大于第二个对象,如果返回值小于0,表示第一个对象小于第二个对象,如果返回0,则两个对象相等。

定义好默认比较规则后,就可以通过不带参数的Sort方法对集合进行排序,如下所示:

//按照默认规则对集合进行排序

persons.Sort();

//输出所有人姓名

foreach (Person p in persons)

{

    Console.WriteLine(p.Name); //输出次序为"李四"、"张三"、"王五"

}

    实际使用中,经常需要对集合按照多种不同规则进行排序,这就需要定义其他比较规则,可以在Compare方法中定义,该方法属于IComparer<T>泛型接口,请看下面的代码:

class NameComparer : IComparer<Person>

{

    //存放排序器实例

    public static NameComparer Default = new NameComparer();

    //按姓名比较

    public int Compare(Person p1, Person p2)

    {

        return System.Collections.Comparer.Default.Compare(p1.Name, p2.Name);

    }

}

    Compare方法的参数为要进行比较的两个同类型对象,返回值为int类型,返回值处理规则与CompareTo方法相同。其中的Comparer.Default返回一个内置的Comparer对象,用于比较两个同类型对象。

    下面用新定义的这个比较器对集合进行排序:

    还可以通过委托来进行集合排序,首先要定义一个供委托调用的方法,用于存放比较规则,可以用静态方法。请看下面的代码:然后通过内置的泛型委托System.Comparison<T>对集合进行排序:

    可以看到,后两种方式都可以对集合按照指定规则进行排序,但笔者更偏向于使用委托方式,可以考虑把各种比较规则放在一个类中,然后进行灵活调用。

//按照姓名对集合进行排序

persons.Sort(NameComparer.Default);

//输出所有人姓名

foreach (Person p in persons)

{

    Console.WriteLine(p.Name); //输出次序为"李四"、"王五"、"张三"

}class PersonComparison

{

    //按姓名比较

    public static int Name(Person p1, Person p2)

    {

        return System.Collections.Comparer.Default.Compare(p1.Name, p2.Name);

    }

}

    方法的参数为要进行比较的两个同类型对象,返回值为int类型,返回值处理规则与CompareTo方法相同。

System.Comparison<Person> NameComparison = new System.Comparison<Person>(PersonComparison.Name);

persons.Sort(NameComparison);

//输出所有人姓名

foreach (Person p in persons)

{

    Console.WriteLine(p.Name); //输出次序为"李四"、"王五"、"张三"

}

可以看到,后两种方式都可以对集合按照指定规则进行排序,但笔者更偏向于使用委托方式,可以考虑把各种比较规则放在一个类中,然后进行灵活调用。

    泛型集合的搜索

    搜索就是从集合中找出满足特定条件的项,可以定义多个搜索条件,并根据需要进行调用。首先,定义搜索条件,如下所示:

class PersonPredicate

{

    //找出中年人(40岁以上)

    public static bool MidAge(Person p)

    {

        if (p.Age >= 40)

            return true;

        else

            return false;

    }

}

    上面的搜索条件放在一个静态方法中,方法的返回类型为布尔型,集合中满足特定条件的项返回true,否则返回false。

System.Predicate<Person> MidAgePredicate = new System.Predicate<Person>(PersonPredicate.MidAge);

List<Person> MidAgePersons = persons.FindAll(MidAgePredicate);

//输出所有的中年人姓名

foreach (Person p in MidAgePersons)

{

    Console.WriteLine(p.Name); //输出"王五"

}然后通过内置的泛型委托System.Predicate<T>对集合进行搜索:

   

    泛型集合的扩展

    如果要得到集合中所有人的姓名,中间以逗号隔开,那该怎么处理?

    考虑到单个类可以提供的功能是有限的,很自然会想到对List<T>类进行扩展,泛型类也是类,因此可以通过继承来进行扩展。请看下面的代码:

//定义Persons集合类

class Persons : List<Person>

{

    //取得集合中所有人姓名

    public string GetAllNames()

    {

        if (this.Count == 0)

            return "";

        string val = "";

        foreach (Person p in this)

        {

            val += p.Name + ",";

        }

        return val.Substring(0, val.Length - 1);

    }

}

//创建并填充Persons集合

Persons PersonCol = new Persons();

PersonCol.Add(p1);

PersonCol.Add(p2);

PersonCol.Add(p3);

//输出所有人姓名

Console.Write(PersonCol.GetAllNames()); //输出“张三,李四,王五”

List的方法和属性 方法或属性 作用

Capacity 用于获取或设置List可容纳元素的数量。当数量超过容量时,这个值会自动增长。您可以设置这个值以减少容量,也可以调用trin()方法来减少容量以适合实际的元素数目。

Count 属性,用于获取数组中当前元素数量

Item( ) 通过指定索引获取或设置元素。对于List类来说,它是一个索引器。

Add( ) 在List中添加一个对象的公有方法

AddRange( ) 公有方法,在List尾部添加实现了ICollection接口的多个元素

BinarySearch( ) 重载的公有方法,用于在排序的List内使用二分查找来定位指定元素.

Clear( ) 在List内移除所有元素

Contains( ) 测试一个元素是否在List内

CopyTo( ) 重载的公有方法,把一个List拷贝到一维数组内

Exists( ) 测试一个元素是否在List内

Find( ) 查找并返回List内的出现的第一个匹配元素

FindAll( ) 查找并返回List内的所有匹配元素

GetEnumerator( ) 重载的公有方法,返回一个用于迭代List的枚举器

Getrange( ) 拷贝指定范围的元素到新的List内

IndexOf( ) 重载的公有方法,查找并返回每一个匹配元素的索引

Insert( ) 在List内插入一个元素

InsertRange( ) 在List内插入一组元素

LastIndexOf( ) 重载的公有方法,,查找并返回最后一个匹配元素的索引

Remove( ) 移除与指定元素匹配的第一个元素

RemoveAt( ) 移除指定索引的元素

RemoveRange( ) 移除指定范围的元素

Reverse( ) 反转List内元素的顺序

Sort( ) 对List内的元素进行排序

ToArray( ) 把List内的元素拷贝到一个新的数组内

trimToSize( ) 将容量设置为List中元素的实际数目

小结:

    本文着重于介绍运用C# 2.0中的泛型来实现集合,以及对集合功能进行扩展,恰当的运用泛型集合,可以减少很多重复工作,极大的提高开发效率。实际上,集合只不过是泛型的一个典型应用,如果想了解更多关于泛型的知识,可以查阅其他相关资料。希望本文对你有用:


本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/eattonton/archive/2010/03/26/5420798.aspx

 

 

 


 

 

MSDN真是太给力了!!~  ><

 

http://msdn.microsoft.com/zh-cn/library/bfcke1bz%28v=VS.80%29.aspx
 

 

 

Predicate 泛型委托

类型参数

T

要比较的对象的类型。

参数
obj

要按照由此委托表示的方法中定义的条件进行比较的对象。

返回值
如果 obj 符合由此委托表示的方法中定义的条件,则为 true;否则为 false
备注

此委托由 ArrayList 类的几种方法使用,用于在集合中搜索元素。

示例

下面的代码示例使用带有 Array.Find 方法的 Predicate 委托搜索 Point 结构的数组。如果 X 和 Y 字段的乘积大于 100,000,此委托表示的方法 ProductGT10 将返回 trueFind 方法为数组的每个元素调用此委托,在符合测试条件的第一个点处停止。

 
ExpandedBlockStart.gif Predicate 泛型委托
using  System;
using  System.Drawing;

public   class  Example
{
    
public   static   void  Main()
    {
        
//  Create an array of five Point structures.
        Point[] points  =  {  new  Point( 100 200 ), 
            
new  Point( 150 250 ),  new  Point( 250 375 ), 
            
new  Point( 275 395 ),  new  Point( 295 450 ) };

        
//  To find the first Point structure for which X times Y 
        
//  is greater than 100000, pass the array and a delegate
        
//  that represents the ProductGT10 method to the Shared 
        
//  Find method of the Array class. 
        Point first  =  Array.Find(points, ProductGT10);

        
//  Note that you do not need to create the delegate 
        
//  explicitly, or to specify the type parameter of the 
        
//  generic method, because the C# compiler has enough
        
//  context to determine that information for you.

        
//  Display the first structure found.
        Console.WriteLine( " Found: X = {0}, Y = {1} " , first.X, first.Y);
    }

    
//  This method implements the test condition for the Find
    
//  method.
     private   static   bool  ProductGT10(Point p)
    {
        
if  (p.X  *  p.Y  >   100000 )
        {
            
return   true ;
        }
        
else
        {
            
return   false ;
        }
    }
}

/*  This code example produces the following output:

Found: X = 275, Y = 395
 
*/


 



 

http://msdn.microsoft.com/zh-cn/library/a1s5syxa%28v=VS.80%29.aspx

List.BinarySearch 方法 (Int32, Int32, T, 泛型 IComparer)

 

注意:此方法在 .NET Framework 2.0 版中是新增的。

使用指定的比较器在已排序 List 的某个元素范围中搜索元素,并返回该元素从零开始的索引。

命名空间:System.Collections.Generic
程序集:mscorlib(在 mscorlib.dll 中)

 

 

 

参数
index

要搜索的范围从零开始的起始索引。

count

要搜索的范围的长度。

item

要定位的对象。对于引用类型,该值可以为 空引用(在 Visual Basic 中为 Nothing)。

comparer

比较元素时要使用的 IComparer 实现,或者为 空引用(在 Visual Basic 中为 Nothing),表示使用默认比较器 Comparer.Default

返回值
如果找到 item,则为已排序的 List 中 item 的从零开始的索引;否则为一个负数,该负数是大于 item 的第一个元素的索引的按位求补。如果没有更大的元素,则为 Count 的按位求补。

 

 

 异常:

 ArgumentOutOfRangeException
 ArgumentException
 InvalidOperationException

 

 

ExpandedBlockStart.gif 代码
using  System;
using  System.Collections.Generic;

public   class  DinoComparer: IComparer < string >
{
    
public   int  Compare( string  x,  string  y)
    {
        
if  (x  ==   null )
        {
            
if  (y  ==   null )
            {
                
//  If x is null and y is null, they're
                
//  equal. 
                 return   0 ;
            }
            
else
            {
                
//  If x is null and y is not null, y
                
//  is greater. 
                 return   - 1 ;
            }
        }
        
else
        {
            
//  If x is not null...
            
//
             if  (y  ==   null )
                
//  ...and y is null, x is greater.
            {
                
return   1 ;
            }
            
else
            {
                
//  ...and y is not null, compare the 
                
//  lengths of the two strings.
                
//
                 int  retval  =  x.Length.CompareTo(y.Length);

                
if  (retval  !=   0 )
                {
                    
//  If the strings are not of equal length,
                    
//  the longer string is greater.
                    
//
                     return  retval;
                }
                
else
                {
                    
//  If the strings are of equal length,
                    
//  sort them with ordinary string comparison.
                    
//
                     return  x.CompareTo(y);
                }
            }
        }
    }
}

public   class  Example
{
    
public   static   void  Main()
    {
        List
< string >  dinosaurs  =   new  List < string > ();

        dinosaurs.Add(
" Pachycephalosaurus " );
        dinosaurs.Add(
" Parasauralophus " );
        dinosaurs.Add(
" Amargasaurus " );
        dinosaurs.Add(
" Galimimus " );
        dinosaurs.Add(
" Mamenchisaurus " );
        dinosaurs.Add(
" Deinonychus " );
        dinosaurs.Add(
" Oviraptor " );
        dinosaurs.Add(
" Tyrannosaurus " );

        
int  herbivores  =   5 ;
        Display(dinosaurs);

        DinoComparer dc 
=   new  DinoComparer();

        Console.WriteLine(
" \nSort a range with the alternate comparer: " );
        dinosaurs.Sort(
0 , herbivores, dc);
        Display(dinosaurs);

        Console.WriteLine(
" \nBinarySearch a range and Insert \ " { 0 }\ " : " ,
            
" Brachiosaurus " );

        
int  index  =  dinosaurs.BinarySearch( 0 , herbivores,  " Brachiosaurus " , dc);

        
if  (index  <   0 )
        {
            dinosaurs.Insert(
~ index,  " Brachiosaurus " );
            herbivores
++ ;
        }

        Display(dinosaurs);
    }

    
private   static   void  Display(List < string >  list)
    {
        Console.WriteLine();
        
foreach string  s  in  list )
        {
            Console.WriteLine(s);
        }
    }
}

/*  This code example produces the following output:

Pachycephalosaurus
Parasauralophus
Amargasaurus
Galimimus
Mamenchisaurus
Deinonychus
Oviraptor
Tyrannosaurus

Sort a range with the alternate comparer:

Galimimus
Amargasaurus
Mamenchisaurus
Parasauralophus
Pachycephalosaurus
Deinonychus
Oviraptor
Tyrannosaurus

BinarySearch a range and Insert "Brachiosaurus":

Galimimus
Amargasaurus
Brachiosaurus
Mamenchisaurus
Parasauralophus
Pachycephalosaurus
Deinonychus
Oviraptor
Tyrannosaurus
 
*/


 

 

 


 

 

 

http://msdn.microsoft.com/zh-cn/library/fh1w7y8z%28v=VS.80%29.aspx

List.FindAll 方法

 

 

参数
match

Predicate 委托,用于定义要搜索的元素应满足的条件。

返回值
如果找到,则为一个 List,其中包含与指定谓词所定义的条件相匹配的所有元素;否则为一个空 List

 

 

 

 

 

ExpandedBlockStart.gif 代码
using  System;
using  System.Collections.Generic;

public   class  Example
{
    
public   static   void  Main()
    {
        List
< string >  dinosaurs  =   new  List < string > ();

        dinosaurs.Add(
" Compsognathus " );
        dinosaurs.Add(
" Amargasaurus " );
        dinosaurs.Add(
" Oviraptor " );
        dinosaurs.Add(
" Velociraptor " );
        dinosaurs.Add(
" Deinonychus " );
        dinosaurs.Add(
" Dilophosaurus " );
        dinosaurs.Add(
" Gallimimus " );
        dinosaurs.Add(
" Triceratops " );

        Console.WriteLine();
        
foreach ( string  dinosaur  in  dinosaurs)
        {
            Console.WriteLine(dinosaur);
        }

        Console.WriteLine(
" \nTrueForAll(EndsWithSaurus): {0} " ,
            dinosaurs.TrueForAll(EndsWithSaurus));

        Console.WriteLine(
" \nFind(EndsWithSaurus): {0} "
            dinosaurs.Find(EndsWithSaurus));

        Console.WriteLine(
" \nFindLast(EndsWithSaurus): {0} " ,
            dinosaurs.FindLast(EndsWithSaurus));

        Console.WriteLine(
" \nFindAll(EndsWithSaurus): " );
        List
< string >  sublist  =  dinosaurs.FindAll(EndsWithSaurus);

        
foreach ( string  dinosaur  in  sublist)
        {
            Console.WriteLine(dinosaur);
        }

        Console.WriteLine(
            
" \n{0} elements removed by RemoveAll(EndsWithSaurus). "
            dinosaurs.RemoveAll(EndsWithSaurus));

        Console.WriteLine(
" \nList now contains: " );
        
foreach ( string  dinosaur  in  dinosaurs)
        {
            Console.WriteLine(dinosaur);
        }

        Console.WriteLine(
" \nExists(EndsWithSaurus): {0} "
            dinosaurs.Exists(EndsWithSaurus));
    }

    
//  Search predicate returns true if a string ends in "saurus".
     private   static   bool  EndsWithSaurus(String s)
    {
        
if  ((s.Length  >   5 &&  
            (s.Substring(s.Length 
-   6 ).ToLower()  ==   " saurus " ))
        {
            
return   true ;
        }
        
else
        {
            
return   false ;
        }
    }
}

/*  This code example produces the following output:

Compsognathus
Amargasaurus
Oviraptor
Velociraptor
Deinonychus
Dilophosaurus
Gallimimus
Triceratops

TrueForAll(EndsWithSaurus): False

Find(EndsWithSaurus): Amargasaurus

FindLast(EndsWithSaurus): Dilophosaurus

FindAll(EndsWithSaurus):
Amargasaurus
Dilophosaurus

2 elements removed by RemoveAll(EndsWithSaurus).

List now contains:
Compsognathus
Oviraptor
Velociraptor
Deinonychus
Gallimimus
Triceratops

Exists(EndsWithSaurus): False
 
*/



 

 

 

http://msdn.microsoft.com/zh-cn/library/234b841s%28VS.80%29.aspx

List.Sort 方法 (泛型 IComparer)

 

 

 

注意:此方法在 .NET Framework 2.0 版中是新增的。

使用指定的比较器对整个 List 中的元素进行排序。

命名空间:System.Collections.Generic
程序集:mscorlib(在 mscorlib.dll 中)

 

 

参数
comparer

比较元素时要使用的 IComparer 实现,或者为 空引用(在 Visual Basic 中为 Nothing),表示使用默认比较器 Comparer.Default

异常:

 

 

 

 

 

示例

下面的代码示例演示 Sort(泛型 IComparer) 方法重载和 BinarySearch(T,泛型 IComparer) 方法重载。

该代码示例定义一个名为 DinoCompare 的代用字符串比较器,该比较器实现 IComparer<string>(在 Visual Basic 中为 IComparer(Of String),Visual C++ 中为 IComparer<String^>)泛型接口。该比较器的工作方式如下:首先测试要进行比较的字符串是否为 空引用(在 Visual Basic 中为 Nothing),空引用被视为小于非空引用。然后,比较字符串的长度,长度越大,则字符串越大。最后,如果长度相等,则使用常规字符串比较方式。

该示例创建一个字符串 List,并用四个字符串进行填充,无固定填充顺序。该示例显示列表,使用该代用比较器对它进行排序并再次显示该列表。

随后,该示例使用 BinarySearch(T,泛型 IComparer) 方法重载搜索几个不在列表中的字符串,从而利用该代用比较器。 Insert 方法用于插入字符串。这两个方法位于名为 SearchAndInsert 的函数中,该函数中还有执行以下操作的代码:对 BinarySearch(T,泛型 IComparer) 返回的负数进行按位求补(C# 和 Visual C++ 中的 ~ 运算符,Visual Basic 中的 Xor -1),并将所得结果用作插入新字符串时的索引
 

 

 

ExpandedBlockStart.gif 代码
using  System;
using  System.Collections.Generic;

public   class  DinoComparer: IComparer < string >
{
    
public   int  Compare( string  x,  string  y)
    {
        
if  (x  ==   null )
        {
            
if  (y  ==   null )
            {
                
//  If x is null and y is null, they're
                
//  equal. 
                 return   0 ;
            }
            
else
            {
                
//  If x is null and y is not null, y
                
//  is greater. 
                 return   - 1 ;
            }
        }
        
else
        {
            
//  If x is not null...
            
//
             if  (y  ==   null )
                
//  ...and y is null, x is greater.
            {
                
return   1 ;
            }
            
else
            {
                
//  ...and y is not null, compare the 
                
//  lengths of the two strings.
                
//
                 int  retval  =  x.Length.CompareTo(y.Length);

                
if  (retval  !=   0 )
                {
                    
//  If the strings are not of equal length,
                    
//  the longer string is greater.
                    
//
                     return  retval;
                }
                
else
                {
                    
//  If the strings are of equal length,
                    
//  sort them with ordinary string comparison.
                    
//
                     return  x.CompareTo(y);
                }
            }
        }
    }
}

public   class  Example
{
    
public   static   void  Main()
    {
        List
< string >  dinosaurs  =   new  List < string > ();
        dinosaurs.Add(
" Pachycephalosaurus " );
        dinosaurs.Add(
" Amargasaurus " );
        dinosaurs.Add(
" Mamenchisaurus " );
        dinosaurs.Add(
" Deinonychus " );
        Display(dinosaurs);

        DinoComparer dc 
=   new  DinoComparer();

        Console.WriteLine(
" \nSort with alternate comparer: " );
        dinosaurs.Sort(dc);
        Display(dinosaurs);

        SearchAndInsert(dinosaurs, 
" Coelophysis " , dc);
        Display(dinosaurs);

        SearchAndInsert(dinosaurs, 
" Oviraptor " , dc);
        Display(dinosaurs);

        SearchAndInsert(dinosaurs, 
" Tyrannosaur " , dc);
        Display(dinosaurs);

        SearchAndInsert(dinosaurs, 
null , dc);
        Display(dinosaurs);
    }

    
private   static   void  SearchAndInsert(List < string >  list, 
        
string  insert, DinoComparer dc)
    {
        Console.WriteLine(
" \nBinarySearch and Insert \ " { 0 }\ " : " , insert);

        
int  index  =  list.BinarySearch(insert, dc);

        
if  (index  <   0 )
        {
            list.Insert(
~ index, insert);
        }
    }

    
private   static   void  Display(List < string >  list)
    {
        Console.WriteLine();
        
foreach string  s  in  list )
        {
            Console.WriteLine(s);
        }
    }
}

/*  This code example produces the following output:

Pachycephalosaurus
Amargasaurus
Mamenchisaurus
Deinonychus

Sort with alternate comparer:

Deinonychus
Amargasaurus
Mamenchisaurus
Pachycephalosaurus

BinarySearch and Insert "Coelophysis":

Coelophysis
Deinonychus
Amargasaurus
Mamenchisaurus
Pachycephalosaurus

BinarySearch and Insert "Oviraptor":

Oviraptor
Coelophysis
Deinonychus
Amargasaurus
Mamenchisaurus
Pachycephalosaurus

BinarySearch and Insert "Tyrannosaur":

Oviraptor
Coelophysis
Deinonychus
Tyrannosaur
Amargasaurus
Mamenchisaurus
Pachycephalosaurus

BinarySearch and Insert "":


Oviraptor
Coelophysis
Deinonychus
Tyrannosaur
Amargasaurus
Mamenchisaurus
Pachycephalosaurus
 
*/


 

 



 

 泛型绑定下拉框

1.

 

#region 绑定下拉框的各种类别
       public void ListBind(List<Model.CateModel> getList, DropDownList dropName)
       {
           List<Model.CateModel> list = getList;
           for (int i = 0; i < list.Count; i++)
           {
               ListItem li = new ListItem();
               li.Text = list[i].cateValue;
               li.Value = list[i].cateCode;
               dropName.Items.Add(li);
               dropName.DataTextField = li.Text;
               dropName.DataValueField = li.Value;
           }
       }
        #endregion

 2.

 

asp.net:如何将枚举绑定到下拉框(DropDownList控件)

先来看一个枚举定义,如下代码:

public enum AlbumType

{

  a,

  b,

  c,

  d,

  e,

  f,

  g,

  h,

  i,

  g,

}

一、直接将枚举的所有值转换成一个List<string>,然后就可以绑定到DropDownList控件上。

代码示例:

   List<string> a = Enum.GetNames(typeof(AlbumType)).ToList<string>();

   DropDownList1.DataSource = a;

 DropDownList1.DataBind();

这个方法比较简单,简洁!如果想将选中的枚举值转换成int型的话,只需要用SelectedIndex就可以获取了,很方便!但是有的时候要向下拉框中添加一个所有相册类型的选择,这时就会比较麻烦了,不过用刚才的方法还是可以实现的,下面就举个例子:

List<string> a = new List<string>();
            a.Add("所有类型");
            a.AddRange(Enum.GetNames(typeof(AlbumType)).ToList<string>());

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

      a.Add("所有类型");

      a.AddRange(Enum.GetNames(typeof(AlbumType)).ToList<string>());

  DropDownList1.DataSource = a;

    DropDownList1.DataBind();

这样只需要将获得的SelectedIndex减去1就是选中枚举值转换成int型的结果(程序中将“所有类型”认为是-1),这样就实现了刚才的需要!

二、刚才第一种方法虽然实现了基本的功能,不过还可以使用List<ListItem>来实现,下面也举一个例子:

    List<ListItem> albumType = new List<ListItem>();

            albumType.Add(new ListItem("所有类型", "-1"));

            foreach(AlbumType type in Enum.GetValues(typeof(AlbumType)))

            {

                albumType.Add(new ListItem(type.ToString(), ((int)type).ToString()));

            }

            DropDownList1.DataSource = albumType;

            DropDownList1.DataTextField = "text";

            DropDownList1.DataValueField = "value";

            DropDownList1.DataBind();

这样实现的话,就不用像前面的方法那样对不上枚举中的值一定要将其认为的-1,这样实现的话使用SelectedValue就是其枚举转换成int型的结果(注意此处为string类型)。

以上两种方法各有优势,推荐使用第一种方法,更简洁一点!

 

 

 

 3.

ExpandedBlockStart.gif 代码
      在前面的文章里,讲了些方法,如果大家仔细体会的其实都还是老的一套方法,根本没有体现面向对象过程编程的思想。并且前面2篇文章的那种方法,代码的重复利用率不高。

       我们可以把DDLItem表给对象化,把表里的字段当作其属性,我先创建个对象类,类名为DDLItemInfo,代码如下所示:

using  System;

 

namespace  BindDropDownList

{

    
///   <summary>

    
///  主要是把DDLItem表对象化,

    
///  把表的字段变为属性,可以任意的

    
///  获取或设置该属性的值。

    
///   </summary>

    
public   class  DDLItemInfo

    {

        
// 定义内部变量

        
private   int  _id;

        
private   string  _ItemName;

 

        
// 定义2重构造函数

        
public  DDLItemInfo(){}

 

        
public  DDLItemInfo(  int  id,  string  ItemName )

        {

            _id 
=  id;

            _ItemName 
=  ItemName;

        }

 

        
// 定义成员的方法

        
public   int  id

        {

            
get

            {

                
return  _id;

            }

            
set

            {

                _id 
=  value;

            }

        }

 

        
public   string  ItemName

        {

            
get

            {

                
return  _ItemName;

            }

            
set

            {

                _ItemName 
=  value;

            }

        }

    }

}

然后创建为该表使用的方法的类库,类名DDLItem.cs,代码如下所示:

using  System;

using  System.Collections;

using  System.Data;

using  System.Data.SqlClient;

 

namespace  BindDropDownList

{

    
///   <summary>

    
///  对DDLItem 表的各种SQL操作。

    
///   </summary>

    
public   class  DDLItem

    {

        
public  DDLItem(){}

 

        
// 定义数据库连接字串

        
private   const   string  SQL_CONN_STRING  =  System.Configuration.ConfigurationSettings.AppSettings[ " ConnectionString " ];

       

        
// 定义SQL语句

        
private   const   string  SQL_SELECT_DDLIIEMS  =   " select id, ItemName from DDLItem order by id desc " ;

       

        
// 构造一个方法来读取所有的DDLItem表里的记录

        
public  IList Get_DDLItems()

        {

            
// 实例化一个可动态增加长度的数组

            IList itemList 
=   new  ArrayList();

            
// 定义数据库连接

            SqlConnection myConn 
=   new  SqlConnection( SQL_CONN_STRING );

            
// 定义SQL命令

            SqlCommand myCommand 
=   new  SqlCommand( SQL_SELECT_DDLIIEMS, myConn );

            
// 打开数据库

            myCommand.Connection.Open();

            
// 定义一个SqlDataReader

            SqlDataReader rdr 
=  myCommand.ExecuteReader();

            
// 开始循环读取记录

            
while ( rdr.Read() )

            {

                
// 构造一个实例化的DDLItem表对象

                DDLItemInfo itemInfo 
=   new  DDLItemInfo(

                    rdr.IsDBNull( 
0  )  ?   0  : rdr.GetInt32(  0  ),

                    rdr.IsDBNull( 
1  )  ?   string .Empty : rdr.GetString(  1  )

                    );

                itemList.Add( itemInfo );

            }

            
// 关闭SqlDataReader和SqlConnection

            rdr.Close();

            myCommand.Connection.Close();

  

            
return  itemList;

        }

       

    }

}

 

上面就把我们要操作的方法都定义好了,下面就是怎么调用的问题了,再创建一个Aspx的页面,代码如下所示:

using  System;

using  System.Collections;

using  System.ComponentModel;

using  System.Data;

using  System.Drawing;

using  System.Web;

using  System.Web.SessionState;

using  System.Web.UI;

using  System.Web.UI.WebControls;

using  System.Web.UI.HtmlControls;

 

namespace  BindDropDownList

{

    
///   <summary>

    
///  Example3 的摘要说明。

    
///   </summary>

    
public   class  Example3 : System.Web.UI.Page

    {

        
protected  System.Web.UI.WebControls.DropDownList DropDownList1;

        
protected  System.Web.UI.WebControls.Button Button1;

   

        
private   void  Page_Load( object  sender, System.EventArgs e)

        {

            
//  在此处放置用户代码以初始化页面

        }

 

        
#region  Web Form Designer generated code

        
override   protected   void  OnInit(EventArgs e)

        {

            
//

            
//  CODEGEN:该调用是 ASP.NET Web 窗体设计器所必需的。

            
//

            InitializeComponent();

            
base .OnInit(e);

        }

       

        
///   <summary>

        
///  设计器支持所需的方法 - 不要使用代码编辑器修改

        
///  此方法的内容。

        
///   </summary>

        
private   void  InitializeComponent()

        {   

            
this .Button1.Click  +=   new  System.EventHandler( this .Button1_Click);

            
this .Load  +=   new  System.EventHandler( this .Page_Load);

 

        }

        
#endregion

 

        
private   void  Button1_Click( object  sender, System.EventArgs e)

        {

            
// 使用DDLItem类的Get_DDLItems方法,取得记录

            IList list 
=   new  DDLItem().Get_DDLItems();

            
// 判断有没有记录

            
if ( list.Count  !=   0  )

            {

                
// 把记录加到DropDownList1上

                
for int  i  =   0  ; i  <  list.Count; i ++  )

                {

                     DDLItemInfo itemInfo 
=  ( DDLItemInfo )list[i];

                     DropDownList1.Items.Add( 
new  ListItem( itemInfo.ItemName, itemInfo.id ) );

                }

            }

          

        }

    }

}

  

这个话,我们在以后管理DDLItem内容时,直接调用Get_DDLItems这个方法就可以列出所有的DDLItem信息,并且一次开发完毕后,对于DDLItem表的结构,通过DDLItemInfo类的属性就能一清二楚的知道,这样也提高效率。

 


4. 例子

ExpandedBlockStart.gif 代码


如果你返回的泛型数据集没有问题,是不会出错的。

测试代码:

< asp:DropDownList ID = " ddlTest "  DataTextField = " Name "  DataValueField = " ID "  runat = " server " ></ asp:DropDownList >

 

namespace  DotNetBS.Web
{
    
public   partial   class  Error : System.Web.UI.Page
    {
        
protected   void  Page_Load( object  sender, EventArgs e)
        {
            
if  ( ! IsPostBack)
            {
                List
< CatalogInfo >  list  =   new  List < CatalogInfo > ();
                CatalogInfo info 
=   new  CatalogInfo() { ID  =   1 , Name  =   " 选项一 "  };
                list.Add(info);
                info 
=   new  CatalogInfo() { ID  =   2 , Name  =   " 选项二 "  };
                list.Add(info);
                ddlTest.DataSource 
=  list;
                ddlTest.DataBind();
            }
        }
    }
    
public   class  CatalogInfo
    {
        
private   int  id;
        
private   string  name;
        
public   int  ID
        {
            
get  {  return  id; }
            
set  { id  =  value; }
        }
        
public   string  Name
        {
            
get  {  return  name; }
            
set  { name  =  value; }
        }
        
public  CatalogInfo() { }
    }
}

 

<asp:DropDownList ID="ddlTest" DataTextField="Name" DataValueField="ID" runat="server"></asp:DropDownList>
可以在前台这么定义,也可以像绑定gridview一样在后台设置

 

 

 

转载于:https://www.cnblogs.com/neru/archive/2011/01/06/1927493.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值