首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > .NET >

LINQ可否直接类型转换

2013-01-12 
LINQ能否直接类型转换以下问题,下述写法需要建立一个lll序列逐步便利,能否让var NewList from p in BigL

LINQ能否直接类型转换
以下问题,下述写法需要建立一个lll序列逐步便利,能否让
var NewList = from p in BigList select new Small { id = p.id };直接转换为List<int>
即:List<int> NewList = from p in BigList select new { id = p.id };,但是这么写不好用

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Web
{
    class Article
    {
        public int? id;
        public string nr;
    }

    public partial class Test : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                List<Article> ArticleList = new List<Article>();
                ArticleList.Add(new Article { id = 1, nr = "11" });
                ArticleList.Add(new Article { id = 2, nr = "22" });
                ArticleList.Add(new Article { id = 3, nr = "33" });
                ArticleList.Add(new Article { id = 4, nr = "44" });
                ArticleList.Add(new Article { id = 5, nr = "55" });

                //NewList是对ArticleList的加工
                var NewList = from p in ArticleList where p.id<=3 select new { id = p.id };
  
                List<int> lll = new List<int>();
                foreach (var p in NewList)
                {
                    lll.Add(Convert.ToInt32(p.id));
                }
                //问题:上述写法需要建立一个lll序列逐步便利,能否让
                //var NewList = from p in BigList select new Small { id = p.id };直接转换为List<int>
                //即:List<int> NewList = from p in BigList select new { id = p.id };,但是这么写不好用


            }
        }
    }
}
[解决办法]
List<int> lll = NewList.Select(p => p.id).ToList();
[解决办法]
List<int> lll = NewList.Select(p => p.id).Where(p => p.HasValue).Select(p=>p.Value).ToList();
[解决办法]
List<int> lll = NewList.Select(p => (int)p.id).ToList();
[解决办法]
直接类型转换
List<int> list= NewList.Select(p => Convert.ToInt32(p.id)).ToList();

热点排行