文章内容

2017/5/23 9:54:17,作 者: 黄兵

C#对多个集合和数组的操作(合并,去重,判断)

在开发过程中.数组和集合的处理是最让我们担心.一般会用for or foreach 来处理一些操作.这里介绍一些常用的集合跟数组的操作函数. 

首先举例2个集合A,B. 

 List<int> listA = new List<int> {1,2,3,5,7,9};

 List<int> listB = new List<int> {13,4,17,29,2};

 

 listA.AddRange(listB );把集合A.B合并
 List<int> Result = listA.Union(listB).ToList<int>();          //剔除重复项 
 List<int> Result = listA.Concat(listB).ToList<int>();        //保留重复项

 listA.BinarySearch("1");//判断集合中是否包含某个值.如果包含则返回0

 

在举例两个数组

  int[] i=new int[]{1,2};
  int[] j=new int[]{2,3};
  List<int> r = new List<int>();  

  r.AddRange(i);

  r.AddRange(j);

  int[] c = r.ToArray(); 合并数组

  int[] x=i.Union(j).ToArray<int>(); //剔除重复项 

  int[] x=i.Concat(j).ToArray<int>(); //保留重复项

  int n = Array.BinarySearch(i,3);//判断数组中是否包含某个值.如果包含则返回0

另外一种方法:

IEnumerable<BlogViewModel> resultDatabase = blog
.Select(m => new BlogViewModel
{
AuthorName = m.User.UserName,
CommentsCount = m.Comments.Count,
CreationTime = m.CreationTime,
Id = m.Id,
Overview = m.Body,
Title = m.Title,
UpdateTime = m.UpdateTime
}).OrderByDescending(b => b.CreationTime).Where(x=>x.Id<=647)
.Skip(start)
.Take(queryOptions.PageSize).ToList();

List<BlogViewModel> result = null;

result = SearchList(keyword,CurrentPage,queryOptions.PageSize);

int pageSie = ParamUrl.CheckPageSize(queryOptions.PageSize, queryOptions.PageSize);
//计数器停止
sw.Stop();
foreach(var item in resultDatabase)
{
result.Add(item);
}

也就是采用了一次循环直接加进去,有时候用listA.AddRange(listB );把集合A.B合并这种方式会提示:

“无法将类型“void”隐式转换为“object”,采用循环则很好的避免了此问题。

分享到:

发表评论

评论列表