扩展 IEnumerable<T>,让它根据另一个集合的顺序来排列
假如我有两个集合:
public class Teacher
{
public int Id { get; set; } public string Name { get; set; }
} public class Student
{
public int Id { get; set; } public string UserName { get; set; } public int TeacherId { get; set; }
}
集合代码:
static void Main(string[] args)
{
IEnumerable<Teacher> teachers = new Teacher[]
{
new Teacher{ Id = , Name = "CCC" },
new Teacher{ Id = , Name = "AAA" },
new Teacher{ Id = , Name = "BBB" },
new Teacher{ Id = , Name = "DDD" },
}; IEnumerable<Student> students = new Student[]
{
new Student{ Id = , TeacherId = , UserName = "张三" },
new Student{ Id = , TeacherId = , UserName = "李四" },
new Student{ Id = , TeacherId = , UserName = "王五" },
new Student{ Id = , TeacherId = , UserName = "赵六" },
};
}
前提条件:students 里面的 TeacherId 大部分来自于 teachers 里的 ID, 也可能不是。
现在要求:按 teachers 的 顺序 来对 students 里面的项排序。
我的代码如下:
首先扩展 IEnumerable<T>
public static class EnumerableExtensions
{
/// <summary>
/// 按照另一个现有的集合的关联字段来排序
/// </summary>
/// <typeparam name="T">类型1</typeparam>
/// <typeparam name="T2">类型2</typeparam>
/// <param name="source1">要排序的集合</param>
/// <param name="source2">参考的集合</param>
/// <param name="condition">条件</param>
/// <returns></returns>
public static IEnumerable<T> OrderByOther<T, T2>(this IEnumerable<T> source1, IEnumerable<T2> source2, Func<T, T2, bool> condition)
{
if (source1 == null)
{
throw new ArgumentNullException("source1");
}
if (source2 == null)
{
throw new ArgumentNullException("source2");
}
if (condition == null)
{
throw new ArgumentNullException("condition");
}
int source1Count = source1.Count();
SortedDictionary<int, T> values = new SortedDictionary<int, T>();
// 3, 0, 2, -1, -1
for (int i = ; i < source1Count; i++)
{
var item = source1.ElementAt(i);
var tempIndex = source2.FirstIndex(s => condition(item, s));
values.Add(tempIndex, item);
}
foreach (var item in values)
{
yield return item.Value;
}
} /// <summary>
/// 得到满足条件的第一个元素在集合中所在的索引
/// </summary>
/// <typeparam name="T">类型</typeparam>
/// <param name="source">目标集合</param>
/// <param name="condition">条件</param>
/// <returns>如果没有找到,返回 -1</returns>
public static int FirstIndex<T>(this IEnumerable<T> source, Predicate<T> condition)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
if (condition == null)
{
throw new ArgumentNullException("condition");
}
int i = ;
foreach (var item in source)
{
if (condition(item))
{
return i;
}
i++;
}
return -;
}
}
然后测试代码如下:
static void Main(string[] args)
{
IEnumerable<Teacher> teachers = new Teacher[]
{
new Teacher{ Id = , Name = "CCC" },
new Teacher{ Id = , Name = "AAA" },
new Teacher{ Id = , Name = "BBB" },
new Teacher{ Id = , Name = "DDD" },
}; IEnumerable<Student> students = new Student[]
{
new Student{ Id = , TeacherId = , UserName = "张三" },
new Student{ Id = , TeacherId = , UserName = "李四" },
new Student{ Id = , TeacherId = , UserName = "王五" },
new Student{ Id = , TeacherId = , UserName = "赵六" },
}; // 前提条件:students 里面的 TeacherId 大部分来自于 teachers 里的 ID, 也可能不是。
// 现在要求:按 teachers 的 顺序 来对 students 里面的项排序。 var result = students.OrderByOther(teachers, (a, b) => a.TeacherId == b.Id);
foreach (var item in result)
{
Console.WriteLine("stuId:" + item.TeacherId + ", stuName:" + item.UserName);
}
}
运行结果:

谢谢浏览!
扩展 IEnumerable<T>,让它根据另一个集合的顺序来排列的更多相关文章
- 管理员技术(六): 硬盘分区及格式化、 新建一个逻辑卷、调整现有磁盘的分区、扩展逻辑卷的大小、添加一个swap分区
一.硬盘分区及格式化 问题: 本例要求熟悉硬盘分区结构,使用fdisk分区工具在磁盘 /dev/vdb 上按以下要求建立分区: 1> 采用默认的 msdos 分区模式 2> ...
- 返回一个集合对象,同时这个集合的对象的属性又是一个集合对象的处理方法(ViewModel)
如果遇到需要返回一个集合对象,其中该集合中的属性又是一个集合.第一种:可在考虑用外键关联,比如在控制器中可以采用预先加载的方式加载关联的数据,比如 RoleManager.Roles.Include& ...
- WorkFlow WF如何为一个集合赋值
今天刚刚开始学习WorkFlow.无奈WF网络上的学习资料实在太少. 刚刚学到Foreach控制流的使用,需要一个集合参数.经研究,静态赋值可以搞定.动态赋值还没. 首先添加一个List<int ...
- PHP的排列组合问题 分别从每一个集合中取出一个元素进行组合,问有多少种组合?
首先说明这是一个数学的排列组合问题C(m,n) = m!/(n!*(m-n)!) 比如:有集合('粉色','红色','蓝色','黑色'),('38码','39码','40码'),('大号','中号') ...
- 将DataTable 存到一个集合当中
将DataTable 存到一个集合中 此做法来自:http://www.codeproject.com/Articles/692832/Simple-way-of-using-SQL-DataTabl ...
- 5.非关系数据库(Nosql)它mongodb:创建一个集合,导出和导入备份, 数据恢复,进出口
1 固定集合 固定集合值得是事先创建并且大小固定的集合 2 固定集合的特征:固定集合非常像环形队列.假设空间不足,最早文档就会被删除,为新的文档腾出空间.一般来说.固定集合适用于不论什么想要自己 ...
- ZOJ 1204 一个集合能组成多少个等式
Additive equations Time Limit : 20000/10000ms (Java/Other) Memory Limit : 65536/32768K (Java/Other ...
- hibernate,createCriteria in条件 是一个集合。list 或 数组等
hibernate,createCriteria in条件 是一个集合.list 或 数组等 cq.in("states", new String[]{"2", ...
- <c:forEach>可以默认的把以逗号分隔的字符串作为一个集合来遍历
<c:forEach>可以默认的把以逗号分隔的字符串作为一个集合来遍历
随机推荐
- node.js WebService异常处理(domain)以及利用domain实现request生命周期的全局变量
成熟的Web Service技术,例如Fast CGI.J2EE.php,必然会对代码异常有足够的保护,好的Web必然会在出错后给出友好的提示,而不是莫名其妙的等待504超时.而node.js这里比较 ...
- 如何安装、配置Apache
Apache的安装流程网上版本很多,但很多版本有错误,或者缺漏,如果初学者按照那样安装的话会遇到各种各样的问题.我整理了自己安装.配置Apache的过程,亲测有效,分享给大家. 基本过程如下: Dow ...
- (二)关于ajax那些事
哈哈,今天突然兴起,想了想自己对ajax的了解,来这里叙述下.心情好,嘿嘿嘿 ajax是一种创建交互式网页应用的网页开发技术.就是在不重新加载页面的情况下,更新部分网页. ajax原理:ajax就是相 ...
- java string转为xml
一.使用最原始的javax.xml.parsers,标准的jdk api // 字符串转XML String xmlStr = \"......\"; StringReader s ...
- 转: sql server2008 字段类型详解
bit 整型 bit数据类型是整型,其值只能是0.1或空值.这种数据类型用于存储只有两种可能值的数据,如Yes 或No.True 或False .On 或Off. 注意:很省空间的一种数据类型,如果能 ...
- 1、Orchard商城开发——开发需求
需要开发的功能: 1.商品详情,可添加商品属性,如颜色,尺寸等. 2.商品类别,可显示该类别下的所有商品,可按品牌.颜色.尺寸等检索,并可按价格.销量等排序游览. 3.商品游览记录,收藏商品,加入购物 ...
- Codeforces Round #383 (Div. 2) 题解【ABCDE】
Codeforces Round #383 (Div. 2) A. Arpa's hard exam and Mehrdad's naive cheat 题意 求1378^n mod 10 题解 直接 ...
- mysql设置连接超时时间参数:wait_timeout
[root@ ~]# mysql -h 192.168.0.* -uroot -pEnter password: Welcome to the MySQL monitor. Commands end ...
- android 中 ViewPager 的平常用法 ViewPager+ Views
延续前面几个的经常用到的ViewPager, 直接加载各种不同的 View 工程目录: 代码: public class ViewActivity extends Activity { // 每个Vi ...
- SqlServer查看各个表所占空间大小的sql
CREATE TABLE [dbo].#tableinfo( 表名 [varchar](50) COLLATE Chinese_PRC_CI_AS NULL, 记录数 [int] NULL, 预留空间 ...