非泛型集合使用Linq

有很多老项目的集合继承Ilist 接口 的非泛型集合, 这也导致我们无法直接使有Linq MS 考虑很周全,为了能够让这些集合使用Linq 需要 OfType () Cast 来帮助。

OfType () Cast 都可以让非泛型使用Linq 他们到底有什么区别泥,简单的说, OfType 在碰到不兼容的对象时会忽略它,而Cast 会抛出异常。这听起来有点抽象。 就举个例子吧。

ArrayList list=new ArrayList();

list.Add(1);

list.Add(2);

list.Add("a");

list.Add(4);

   

IEnumerable query =list.OfType ().Where(p=>p<5);

foreach(int i in query)

{

Console.Write(string.Format("{0}-", i));

}

输出:

1

2

4

IEnumerable query1 = list.Cast ().Where(p => p < 5);

foreach (int i in query1)

{

Console.Write(string.Format("{0}-", i));

}

输出:

1

2

3 (时抛出异常 "Specified cast is not valid".,程序终止)。

   

   

大家在做检索的时候, 往往会碰到多个 检索项,如:Name, State,Id, 等等。有很多项。仅仅是在UI进行检索,不是从数据库获得。我们可能 需要在 where()条件中 使用 if else switch 等条件语句,众人周知,在 where() 方法中 无法使用 这些 关键字。 我们应该怎么做呢。 怎么才能够拥一条where完成呢。 举个例子吧:

Public class FileList

{

public Id

{get;set;}

public Name

{get;set;}

public State

{get;set;}

}

   

//AllFileList is collection of FileList , is only implent Ilist and Ienumber interface

//search file

private void SearchFile()

{

//in where method, user a method . This method must be return type is boolean.

IEnumerable query =

AllFileList.OfType ().Where(p=>SearchFile(p));

   

foreach (FileList file in query)

{

SearchFileList.Add(file);

}

}

private bool SearchFile(FileList file)

{

bool flag1 = true;

bool flag2 = true;

   

string name = this.txtSearchName.Text.Trim();

string state = this.cbSearchStatus.SelectedItem.ToString();

   

if (!state.Equals(" "))

{

flag1 = (file.FileState.Name.ToUpper().Equals(state.ToUpper())

|| file.FilePending.ToString().ToUpper().Equals(state.ToUpper()));

}

if (!string.IsNullOrEmpty(name))

{

flag2 = file.CommentFileName.ToUpper().Contains(name.ToUpper());

}

return (flag1 && flag2);

}

   

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值