C#中的数组

1.List<> 常见操作

1.数据

IEnumerable<string> lstNew = null;
List<string> lstOne = new List<string>(){"January", "February", "March"};
List<string> lstTwo = new List<string>() { "January", "April", "March"};
List<string> lstThree = new List<string>() { "January", "April", "March", "May" };
List<string> lstFour = new List<string>() { "Jan", "Feb", "Jan", "April", "Feb" };


2.输入

static void PrintList(IEnumerable<string> str)

{
    foreach (var s in str)
    Console.WriteLine(s);
    Console.WriteLine("-------------");
}


3.常用操作(命名空间:System.Linq)

    Enumberable.Intersect();
    // Compare two List<string> and display common elements
    lstNew = lstOne.Intersect(lstTwo, StringComparer.OrdinalIgnoreCase);
    PrintList(lstNew);


    输出相同元素:JANUARY MARCH
 

       Enumerable.Except
    // Compare two List<string> and display items of lstOne not in lstTwo
    lstNew = lstOne.Except(lstTwo, StringComparer.OrdinalIgnoreCase);
    PrintList(lstNew);
        Enumerable.Distinct
    // Unique List<string>
    lstNew = lstFour.Distinct(StringComparer.OrdinalIgnoreCase);
    PrintList(lstNew)
        List.ConvertAll
    // Convert elements of List<string> to Upper Case
    lstNew = lstOne.ConvertAll(x => x.ToUpper());
    PrintList(lstNew);
        Enumerable.Concat
    // Concatenate and Sort two List<string>
    lstNew = lstOne.Concat(lstTwo).OrderBy(s => s);
    PrintList(lstNew);
        Enumerable.Concat and Enumerable.Distinct
    // Concatenate Unique Elements of two List<string>
    lstNew = lstOne.Concat(lstTwo).Distinct();
    PrintList(lstNew);
        List.Reverse
    // Reverse a List<string>
    lstOne.Reverse();
    PrintList(lstOne);
        List.RemoveAll
    // Search a List<string> and Remove the Search Item
    // from the List<string>
    int cnt = lstFour.RemoveAll(x => x.Contains("Feb"));
    Console.WriteLine("{0} items removed", cnt);
    PrintList(lstFour);
         Enumerable.OrderBy and Enumerable.ThenByDescending
    // Order by Length then by words (descending)
    lstNew = lstThree.OrderBy(x => x.Length)
            .ThenByDescending(x => x);
    PrintList(lstNew);

        Use the Enumerable.Aggregate method
    C#
    // Create a string by combining all words of a List<string>
    // Use StringBuilder if you want performance
    string delim = ",";
    var str = lstOne.Aggregate((x, y) => x + delim + y);
    Console.WriteLine(str);
    Console.WriteLine("-------------");
    
        Split the string and use the Enumerable.ToList method
    C#
    // Create a List<string> from a Delimited string
    string s = "January February March";
    char separator = ' ';
    lstNew = s.Split(separator).ToList();
    PrintList(lstNew);
     
    Use the List(T).ConvertAll method
    C#
    // Convert a List<int> to List<string>
    List<int> lstNum = new List<int>(new int[] { 3, 6, 7, 9 });
    lstNew = lstNum.ConvertAll<string>(delegate(int i)
    {
         return i.ToString();
    });
    PrintList(lstNew);

   Use Enumerable.GroupBy, Enumerable.Select and Enumerable.OrderByDescending
    // Count Repeated Words
    var q = lstFour.GroupBy(x => x)
       .Select(g => new { Value = g.Key, Count = g.Count() })
       .OrderByDescending(x => x.Count);
    foreach (var x in q)
    {
        Console.WriteLine("Value: " + x.Value + " Count: " + x.Count);
    }

关于排序

1.排序1

                    multiSpecialRoute[0].Sort(delegate(CorpFlightSearchFlightEntity x, CorpFlightSearchFlightEntity y)
                    {
                        return x.PrintPrice.CompareTo(y.PrintPrice);
                    });

2.排序2

this._appFlightsList.Sort(AppFlightSorter.CorpSort);
        public static int CorpSort(FlightOnlineAppEntity Entity1, FlightOnlineAppEntity Entity2)
        {
            //起飞时间对比
            int Result = Entity1.DepartTime.CompareTo(Entity2.DepartTime);
            //如果两者的起飞时间不同,按起飞时间排序
            if (Result != 0)
            {
                return Result;
            }
            //如果两者的起飞时间相同,再按价格排序
            else
            {
                Result = Entity1.Flight.Trim().ToUpper().CompareTo(Entity2.Flight.Trim().ToUpper());
                if (Result != 0)
                {
                    return Result;
                }
                else
                {
                    return Entity1.Price.CompareTo(Entity2.Price);
                }

            }
        }

3.移除

this._appFlightsList.RemoveAll(FirstSingleFlightFinder.IsFirstSingleFlight);

        public static bool IsFirstSingleFlight(FlightOnlineAppEntity flight)
        {
            if (flight.PriceType.Trim().ToUpper() != "SINGLETRIPPRICE")
            {
                return false;
            }
            if (flight.Class.Trim().ToUpper() != "F")
            {
                return false;
            }
            return true;
}

4.for循环
一般你会想到for(int i=0;i<count;i++){}这种写法,还可能想到foreach(var item in collection)这种写法,但是下面的写法比较简洁了。

this._appFlightsList.ForEach(ShowFlightsUICommon.SetAppFlight);

        public static void SetAppFlight(FlightOnlineAppEntity flight)

{

            flight.HasTicketLimit = !string.IsNullOrEmpty(flight.TicketLimit);
            flight.HasRecommend = !string.IsNullOrEmpty(flight.RecommendString);

}

还有更加简洁的写法就是用代理,如下,注意这个方法没有返回值,不能写成
List<ChoiceItem> items = row.ChoiceItems.ForEach(delegate(ChoiceItem item) { item.ItemContent = item.Option + "." + item.ItemContent; });

                        CheckBoxList chklist = e.Item.FindControl("chklist") as CheckBoxList;
                        chklist.Visible = true;
                        List<ChoiceItem> items = row.ChoiceItems;
                        items.ForEach(delegate(ChoiceItem item) { item.ItemContent = item.Option + "." + item.ItemContent; });
                        chklist.DataSource = items;
                        chklist.DataTextField = "ItemContent";
                        chklist.DataValueField = "Option";
                        chklist.DataBind();

5.查找,注意只要list不为空,无论他的查找是否符合条件,返回结果都不为空,这一点很省心。
  如果仅仅List<student> list;编译不通过:使用了未赋值的变量list。
  如果仅仅List<student> list = null;这样编译不报错,运行的时候报错:未将对象引用设置到对象实例。
  所以只要List<student> list = new List<student>();可保正常运行。

    public class student
    {
        private int _id;
        private string _name;
        public student(int id, string name)
        {
            this._id = id;
            this._name = name;
        }
        public int ID { get { return _id; } set { _id = value; } }
        public string Name { get { return _name; } set { _name = value; } }
    }

        protected void Button1_Click(object sender, EventArgs e)
        {
            List<student> list = new List<student>();
            list.Add(new student(1, "a"));
            list.Add(new student(2, "b"));
            list.Add(new student(3, "c"));
            list.Add(new student(4, "d"));

            List<student> curr = list.FindAll(delegate(student s) { return s.ID == 6; });

            foreach (student item in curr)
            {
                Response.Write("ID:" + item.ID + "  Name:" + item.Name + "\r\n");
            }
        }

 还有一种简便的写法

List<RecipientEntity> recipient8 = tempConfirmRecList.FindAll(delegate(RecipientEntity re) { return re.MailType == 8; });

List<RecipientEntity> recipient8 = tempConfirmRecList.FindAll(re => re.MailType == 8);

注意括号里面没有;

 

2.IQueryable, IEnumerable, IList的区别

TestIQueryable

private static void TestIQueryable()
{
    using (var ctx = new WrappedNorthWindEntities())
    {
        IQueryable<Product> expression = ctx.Products.Take(5);
        IQueryable<Product> products = expression.Take(2);   // A  不执行SQL
        Console.WriteLine(products.Count());          // B SELECT COUNT(1) FROM ( SELECT TOP (2) * FROM ( SELECT TOP (5) * FROM [dbo].[Products] ))
        Console.WriteLine(products.Count());          // C  SELECT COUNT(1) FROM ( SELECT TOP (2) * FROM ( SELECT TOP (5) * FROM [dbo].[Products] ))
        foreach (Product p in products)             // D  SELECT TOP (2) * FROM ( SELECT TOP (5) * FROM [dbo].[Products] 
        {
            Console.WriteLine(p.ProductName);
        }
        foreach (Product p in products)              // E  SELECT TOP (2) * FROM ( SELECT TOP (5) * FROM [dbo].[Products] )
        {
            Console.WriteLine(p.ProductName);
        }
    }
}
TestIEnumerable

private static void TestIEnumerable()
{
    using (var ctx = new WrappedNorthWindEntities())
    {
        IEnumerable<Product> expression = ctx.Products.Take(5).AsEnumerable();
        IEnumerable<Product> products = expression.Take(2);  // A  不执行SQL
        Console.WriteLine(products.Count());          // B SELECT TOP (5) * FROM [dbo].[Products]
        Console.WriteLine(products.Count());          // C  SELECT TOP (5) * FROM [dbo].[Products]
        foreach (Product p in products)             // D  SELECT TOP (5) * FROM [dbo].[Products] 
        {
            Console.WriteLine(p.ProductName);
        }
        foreach (Product p in products)              // E  SELECT TOP (5) * FROM [dbo].[Products]
        {
            Console.WriteLine(p.ProductName);
        }
    }
}
TestIList

private static void TestIList()
{
    using (var ctx = new WrappedNorthWindEntities())
    {
        var expression = ctx.Products.Take(5);
        IList<Product> products = expression.Take(2).ToList(); // A  SELECT TOP (2) * FROM ( SELECT TOP (5) * FROM [dbo].[Products]

        Console.WriteLine(products.Count());            // B 不执行SQL
        Console.WriteLine(products.Count());            // C  不执行SQL
        foreach (Product p in products)               // D  不执行SQL
        {
            Console.WriteLine(p.ProductName);
        }
        foreach (Product p in products)                // E  不执行SQL
        {
            Console.WriteLine(p.ProductName);
        }
    }
}
  1. IQueryable和IEnumerable都是延时执行(Deferred Execution)的,而IList是即时执行(Eager Execution)
  2. IQueryable和IEnumerable在每次执行时都必须连接数据库读取,而IList读取一次后,以后各次都不需连接数据库。前两者很容易造成重复读取,性能低下,并且可能引发数据不一致性
  3. IQueryable和IEnumerable的区别:IEnumberalb使用的是LINQ to Object方式,它会将AsEnumerable()时对应的所有记录都先加载到内存,然后在此基础上再执行后来的Query。所以上述TestIEnumerable例子中执行的SQL是"select top(5) ...",然后在内存中选择前两条记录返回。

以下是一个IQueryable引发数据不一致性的例子:记录总数和记录详情两者本应一致,但由于IQueryable前后两次读取数据库,结果是现实有10条记录,却输出11条详情。

 

IQueryable Data Inconsistancy

    IQueryable<Product> products = ctx.Products.All();
    //开始的时候数据库product表中有10条记录, count = 10
    int count = products.Count();
    Console.WriteLine("Count of products:"+count);  
        
    //此时另一进程添加一个产品进数据库
    //会重新读取数据库并输出11个产品名称
    foreach (Product p in products)       
    {
    Console.WriteLine(p.ProductName);    
    }

 

基于性能和数据一致性这两点,我们使用IQueryable时必须谨慎,而在大多数情况下我们应使用IList。

    1.当你打算马上使用查询后的结果(比如循环作逻辑处理或者填充到一个table/grid中),并且你不介意该查询会即时执行,使用ToList()
    2.当你希望查询后的结果可以供调用者(Consummer)作后续查询(比如这是一个"GetAll"的方法),或者你希望该查询延时执行,使用AsQueryable()

 

3.Linq操作

1.where过滤查询
使用where筛选在伦敦的客户

var q =
    from c in db.Customers
    where c.City == "London"
    select c;

再如:筛选1994 年或之后雇用的雇员:

var q =
    from e in db.Employees
    where e.HireDate >= new DateTime(1994, 1, 1)
    select e;

筛选库存量在订货点水平之下但未断货的产品:

var q =
    from p in db.Products
    where p.UnitsInStock <= p.ReorderLevel && !p.Discontinued
    select p;

筛选出UnitPrice 大于10 或已停产的产品:

var q =
    from p in db.Products
    where p.UnitPrice > 10m || p.Discontinued
    select p;

调用两次where以筛选出UnitPrice大于10且已停产的产品:

var q =
    db.Products.Where(p=>p.UnitPrice > 10m).Where(p=>p.Discontinued);

返回集合中的一个元素,其实质就是在SQL语句中加TOP (1)
选择表中的第一个发货方

Shipper shipper = db.Shippers.First();

选择CustomerID 为“BONAP”的单个客户

Customer cust = db.Customers.First(c => c.CustomerID == "BONAP");

选择运费大于 10.00 的订单:

Order ord = db.Orders.First(o => o.Freight > 10.00M);

 2.select,distinct
返回仅含客户联系人姓名的序列

var q =
    from c in db.Customers
    select c.ContactName;

这个语句只是一个声明或者一个描述,并没有真正把数据取出来,只有当你需要该数据的时候,它才会执行这个语句,这就是延迟加载(deferred loading)。如果,在声明的时候就返回的结果集是对象的集合。可以使用ToList() 或ToArray()方法把查询结果先进行保存,然后再对这个集合进行查询。当然延迟加载(deferred loading)可以像拼接SQL语句那样拼接查询语法,再执行它。

说明:匿名类型是C#3.0中新特性。其实质是编译器根据我们自定义自动产生一个匿名的类来帮助我们实现临时变量的储存。匿名类型还依赖于另外一个 特性:支持根据property来创建对象。比如,var d = new { Name = "s" };编译器自动产生一个有property叫做Name的匿名类,然后按这个类型分配内存,并初始化对象。但是var d = new {"s"};是编译不通过的。因为,编译器不知道匿名类中的property的名字。例如string c = "d";var d = new { c}; 则是可以通过编译的。编译器会创建一个叫做匿名类带有叫c的property。
例如下 例:new{c,ContactName,c.Phone};ContactName和Phone都是在映射文件中定义与表中字段相对应的 property。编译器读取数据并创建对象时,会创建一个匿名类,这个类有两个属性,为ContactName和Phone,然后根据数据初始化对象。 另外编译器还可以重命名property的名字。
使用 SELECT 和匿名类型返回仅含客户联系人姓名和电话号码的序列

var q =
    from c in db.Customers
    select new {c.ContactName, c.Phone};

使用SELECT和匿名类型返回仅含雇员姓名和电话号码的序列,并将FirstName和LastName字段合并为一个字段“Name”,此外在所得的序列中将HomePhone字段重命名为Phone。

var q =
    from e in db.Employees
    select new
    {
        Name = e.FirstName + " " + e.LastName,
        Phone = e.HomePhone
    };

使用SELECT和匿名类型返回所有产品的ID以及HalfPrice(设置为产品单价除以2所得的值)的序列。

var q =
    from p in db.Products
    select new
    {
        p.ProductID,
        HalfPrice = p.UnitPrice / 2
    };

使用SELECT和条件语句返回产品名称和产品供货状态的序列

var q =
    from p in db.Products
    select new
    {
        p.ProductName,
        Availability =
        p.UnitsInStock - p.UnitsOnOrder < 0 ? 
        "Out Of Stock" : "In Stock"
    };

返回你自定义类型的对象集,使用SELECT和已知类型返回雇员姓名的序列

var q =
    from e in db.Employees
    select new Name
    {
        FirstName = e.FirstName,
        LastName = e.LastName
    };

结合where使用,起到过滤作用,使用SELECT和WHERE返回仅含伦敦客户联系人姓名的序列

var q =
    from c in db.Customers
    where c.City == "London"
    select c.ContactName;

select操作使用了匿名对象,而这个匿名对象中,其属性也是个匿名对象,使用SELECT 和匿名类型返回有关客户的数据的整形子集。查询顾客的ID和公司信息(公司名称,城市,国家)以及联系信息(联系人和职位)

var q =
    from c in db.Customers
    select new {
        c.CustomerID,
        CompanyInfo = new {c.CompanyName, c.City, c.Country},
        ContactInfo = new {c.ContactName, c.ContactTitle}
    };

返回的对象集中的每个对象DiscountedProducts属性中,又包含一个集合。也就是每个对象也是一个集合类,使用嵌套查询返回所有订单及其OrderID 的序列、打折订单中项目的子序列以及免送货所省下的金额

var q =
    from o in db.Orders
    select new {
        o.OrderID,
        DiscountedProducts =
            from od in o.OrderDetails
            where od.Discount > 0.0
            select od,
        FreeShippingDiscount = o.Freight
    };

查询中调用本地方法PhoneNumberConverter将电话号码转换为国际格式

var q = from c in db.Customers
         where c.Country == "UK" || c.Country == "USA"
         select new
         {
             c.CustomerID,
             c.CompanyName,
             Phone = c.Phone,
             InternationalPhone = 
             PhoneNumberConverter(c.Country, c.Phone)
         };

PhoneNumberConverter方法如下:

public string PhoneNumberConverter(string Country, string Phone)
{
    Phone = Phone.Replace(" ", "").Replace(")", ")-");
    switch (Country)
    {
        case "USA":
            return "1-" + Phone;
        case "UK":
            return "44-" + Phone;
        default:
            return Phone;
    }
}

下面也是使用了这个方法将电话号码转换为国际格式并创建XDocument

XDocument doc = new XDocument(
    new XElement("Customers", from c in db.Customers
              where c.Country == "UK" || c.Country == "USA"
              select (new XElement("Customer",
                      new XAttribute("CustomerID", c.CustomerID),
                      new XAttribute("CompanyName", c.CompanyName),
                      new XAttribute("InterationalPhone", 
                       PhoneNumberConverter(c.Country, c.Phone))
                     ))));

筛选字段中不相同的值。用于查询不重复的结果集。生成SQL语句为:SELECT DISTINCT [City] FROM [Customers],查询顾客覆盖的国家

var q = (
    from c in db.Customers
    select c.City )
    .Distinct();

 

posted @ 2013-04-09 16:26  nd  阅读(9269)  评论(2编辑  收藏  举报