假如我有两个集合:

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>,让它根据另一个集合的顺序来排列的更多相关文章

  1. 管理员技术(六): 硬盘分区及格式化、 新建一个逻辑卷、调整现有磁盘的分区、扩展逻辑卷的大小、添加一个swap分区

    一.硬盘分区及格式化 问题: 本例要求熟悉硬盘分区结构,使用fdisk分区工具在磁盘 /dev/vdb 上按以下要求建立分区: 1> 采用默认的 msdos 分区模式        2> ...

  2. 返回一个集合对象,同时这个集合的对象的属性又是一个集合对象的处理方法(ViewModel)

    如果遇到需要返回一个集合对象,其中该集合中的属性又是一个集合.第一种:可在考虑用外键关联,比如在控制器中可以采用预先加载的方式加载关联的数据,比如 RoleManager.Roles.Include& ...

  3. WorkFlow WF如何为一个集合赋值

    今天刚刚开始学习WorkFlow.无奈WF网络上的学习资料实在太少. 刚刚学到Foreach控制流的使用,需要一个集合参数.经研究,静态赋值可以搞定.动态赋值还没. 首先添加一个List<int ...

  4. PHP的排列组合问题 分别从每一个集合中取出一个元素进行组合,问有多少种组合?

    首先说明这是一个数学的排列组合问题C(m,n) = m!/(n!*(m-n)!) 比如:有集合('粉色','红色','蓝色','黑色'),('38码','39码','40码'),('大号','中号') ...

  5. 将DataTable 存到一个集合当中

    将DataTable 存到一个集合中 此做法来自:http://www.codeproject.com/Articles/692832/Simple-way-of-using-SQL-DataTabl ...

  6. 5.非关系数据库(Nosql)它mongodb:创建一个集合,导出和导入备份, 数据恢复,进出口

     1 固定集合 固定集合值得是事先创建并且大小固定的集合 2 固定集合的特征:固定集合非常像环形队列.假设空间不足,最早文档就会被删除,为新的文档腾出空间.一般来说.固定集合适用于不论什么想要自己 ...

  7. ZOJ 1204 一个集合能组成多少个等式

    Additive equations Time Limit : 20000/10000ms (Java/Other)   Memory Limit : 65536/32768K (Java/Other ...

  8. hibernate,createCriteria in条件 是一个集合。list 或 数组等

    hibernate,createCriteria in条件 是一个集合.list 或 数组等 cq.in("states", new String[]{"2", ...

  9. <c:forEach>可以默认的把以逗号分隔的字符串作为一个集合来遍历

    <c:forEach>可以默认的把以逗号分隔的字符串作为一个集合来遍历

随机推荐

  1. paip.取当天记录的方法sql跟hql hibernate

    paip.取当天记录的方法sql跟hql hibernate #------两个方法...函数法和日期计算法.. 函数法: DATEDIFF(d,createTime,GETDATE())=0   / ...

  2. java继承3个小题

    1.实现一个名为Person的类和它的子类Employee,Employee有两个子类Faculty和Staff.具体要求如下: (1)Person类中的属性有:姓名name(String类型),地址 ...

  3. wicket基础应用(1)--使用wicket对表单中的数据进行验证

    作者:lhx1026 出处:http://lhx1026.iteye.com/ wicket基础应用(1)--使用wicket对表单中的数据进行验证 举个例子: 1.有一个Java文件SysCharg ...

  4. IOS开发之控件篇UITabBarControllor第一章 - 介绍

    UITabBarControllor的基本样子 官方有个图介绍这个TabBar的结构,我们先来看看这个结构图 --------------------------------------------- ...

  5. 25数据查询的各种小玩法-select上(必学)-天轰穿sqlserver视频教程

    大纲:简单查询-选择数据列,使用字符串,改变列标题,使用数据运算 优酷超清地址,为了冲优酷的访问量,所以这里只放优酷的地址了,其实其他网站还是都传了的哈.

  6. android网络框架Retrofit 同步异步

    http://blog.csdn.net/jiguangcanhen/article/details/39006197 同步的方式: 1)首先定义要接口.注解Get表示使用的Get请求方式,{user ...

  7. 关于启明星系统移除apppath配置,让系统自动获取路径来设置cookie的解决方法

    启明星系统底层使用统一接口,特别是用户,用户登录后,都会建立一个 userinfo 的cookie.请看下面2个网址: http://120.24.86.232/book http://120.24. ...

  8. 配置android环境

    以下是针对windows 系统 1. 下载Android sdk 到http://developer.android.com/sdk/index.html 下载SDK(windows) 这里会需要很长 ...

  9. 奇怪吸引子---Russler

    奇怪吸引子是混沌学的重要组成理论,用于演化过程的终极状态,具有如下特征:终极性.稳定性.吸引性.吸引子是一个数学概念,描写运动的收敛类型.它是指这样的一个集合,当时间趋于无穷大时,在任何一个有界集上出 ...

  10. Intrinsics头文件与SIMD指令集、Visual Studio版本对应表(转)

    File:Intrinsics头文件 描述:指令集描述VS:Visual Studio版本号VisualStudio:Visual Studio版本名 File 描述 VS VisualStudio ...