C# IEnumerable<int> listID = list.Select(x => x.ID);我想在ID里加条件筛选的话,要怎么写?

C# IEnumerable<int> listID = list.Select(x => x.ID);我想在ID里加条件筛选的话,要怎么写?,第1张

var listID = list.Select(x =>x.ID).Where(...)

Where中是一个返回bool值的方法,比如我想筛选所有ID大于5的项:var listID = list.Select(x =>x.ID).Where(x=>x>5)这样就取出了所有大于5的ID,另外,lambda表达式x=>x>5是(x)=>{return x>5}的简写,更复杂的条件判断可以写在花括号中,但返回值必须是布尔型。Select和Where方法内部是用linq实现的,上面的表达式等价于下面的linq表达式:

var tmp=from x in list select x.ID

var listID=from x in tmp where x>5 select x

合并一下就是

var listID=from x in list where x.ID>5 select x.ID

声明:

1、List<T>mList = new List<T>()

T为列表中元素类型,现在以string类型作为例子

E.g.:List<string>mList = new

List<string>()

2、List<T>testList =new List<T>

(IEnumerable<T>collection)

以一个集合作为参数创建List

E.g.:

string[] temArr = { "Ha", "Hunter", "Tom", "Lily", "Jay", "Jim",

"Kuku", "Locu" }

List<string>testList = new

List<string>(temArr)

添加元素:

1、 List. Add(T item) 添加一个元素

E.g.:mList.Add("John")

2、 List. AddRange(IEnumerable<T>collection) 添加一组元素

E.g.:

string[] temArr = { "Ha","Hunter", "Tom", "Lily", "Jay", "Jim",

"Kuku", "Locu" }

mList.AddRange(temArr)

3、Insert(int index, T item) 在index位置添加一个元素

E.g.:mList.Insert(1, "Hei")

C#.NET的集合主要位于System.Collections和System.Collections.Generic(泛型)这两个namespace中。

1、System.Collections

比如ArrayList,其Add(继承自接口IList)和AddRange方法可用于想集合中添加元素。

代码示例:

(1)Add:添加单个元素

ArrayList myAL = new ArrayList()

myAL.Add( "The" )

myAL.Add( "quick" )

myAL.Add( "brown" )

myAL.Add( "fox" )

(2)AddRange:添加实现了ICollection接口的一个集合的所有元素到指定集合的末尾

ArrayList myAL = new ArrayList()

myAL.Add( "The" )

myAL.Add( "quick" )

myAL.Add( "brown" )

myAL.Add( "fox" )

Queue myQueue = new Queue()

myQueue.Enqueue( "jumped" )

myQueue.Enqueue( "over" )

myQueue.Enqueue( "the" )

myQueue.Enqueue( "lazy" )

myQueue.Enqueue( "dog" )

myAL.AddRange( myQueue )

2、System.Collections.Generic

泛型同样也有Add(继承自ICollection<T>)和AddRange两个方法。

代码示例:

(1)Add:添加单个元素

List<string> dinosaurs = new List<string>()

dinosaurs.Add("Tyrannosaurus")

dinosaurs.Add("Amargasaurus")

dinosaurs.Add("Mamenchisaurus")

dinosaurs.Add("Deinonychus")

dinosaurs.Add("Compsognathus")

(2)AddRange:添加实现了接口IEnumerable<T>的一个泛型集合的所有元素到指定泛型集合末尾

string[] input = { "Brachiosaurus", "Amargasaurus", "Mamenchisaurus" }

List<string> dinosaurs = new List<string>(input)

dinosaurs.AddRange(dinosaurs)

参考资料:

http://msdn.microsoft.com/zh-cn/library/system.collections(v=vs.100).aspx

http://msdn.microsoft.com/zh-cn/library/system.collections.generic(v=vs.100).aspx


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/bake/11359544.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-15
下一篇2023-05-15

发表评论

登录后才能评论

评论列表(0条)

    保存