csharp 匿名对象和列表(C#)。cs

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp 匿名对象和列表(C#)。cs相关的知识,希望对你有一定的参考价值。


//================= Annonymous List/Array ======================
var books = new [] {
  new  { Title = "Prejudice", Price = 1300 },
  new  { Title = "Justice", Price = 1300 },
  new  { Title = "War & Peace", Price = 1700 },
  new  { Title = "Computer Pro", Price = 700 },
};
var selectedBooks = from book in books 
                    where book.price > 1000
                    select book;
foreach(var aBook in selectedBooks) {
  Console.WriteLine(aBook.Title);
}



// ============== GET List of Annonymous Object with Two Field (Text, Value) ======================
private List<object> GetTempCustomers()
{
	var customerList = new List<object>();
	var db = new NORTHWNDEntities();
	foreach (Customer aCustomer in db.Customers)
	{
		customerList.Add(new { Text = aCustomer.ContactName, Value = aCustomer.CustomerID });
	}
	return customerList;
}


/*===================ANNONYMOUS TYPED & IMPLICITLY TYPED ARRAY=====================*/
var item1 = new {Id = "F-001", UnitPrice = 500, Category = "Food"};
var item2 = new { Id = "E-002", UnitPrice = 1000, Category = "Electronics" };
var itemList = new[] {item1, item2};

foreach (var anItem in itemList)
{
    Console.WriteLine(anItem.Id+", "+anItem.UnitPrice+", "+anItem.Category);
}



//=================== Return an Annonymous Object (JSON) =====================
public JsonResult GetOrderInfo(int oId = 0)
{
    SAL_Order aOrder = getOrderInfoById(oId);
    string BranchName = dbContext.MST_Branch.Where(o => o.BranchID == aOrder.BranchID).FirstOrDefault().BranchName.ToString();
    return Json(new
    {
        OrderID = aOrder.OrderID,
        DocNo = aOrder.DocNo,

        DocDate = aOrder.DocDate,
        DocDateForOverview = aOrder.DocDate.ToString(),

        CustomerID = aOrder.CustomerID,
        BranchID = aOrder.BranchID,
        BranchName = BranchName,
        InvoiceType = aOrder.InvoiceType,

        OrderNo = aOrder.OrderNo,
        OrderDate = aOrder.OrderDate,
        OrderDateForOverview = aOrder.OrderDate.ToString(),

        Remark = aOrder.Remark,
        SubTotal = aOrder.SubTotal,
        Discount = aOrder.Discount,
        NetAmount = aOrder.NetAmount,
        DBUserID = aOrder.DBUserID,
        UpdateDateTime = aOrder.UpdateDateTime
    });
}

以上是关于csharp 匿名对象和列表(C#)。cs的主要内容,如果未能解决你的问题,请参考以下文章

csharp 创建按价格订购的3种产品的匿名对象

csharp 具有匿名类型c#的.net mvc json结果

csharp Async C#program.cs

csharp C#.cs中的析构函数

csharp C#或ASP.Net Utility.cs

csharp DB CRUD(C#Windows窗体).cs