今天在学习Linq的基础知识的时候遇到这么一个问题:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 namespace DemoLinq 7 { 8 class Program 9 { 10 public static LinqData dataForTest = new LinqData { Name = "lsb", Score = "85", Age = 15 }; 11 static void Main(string[] args) 12 { 13 List<LinqData> linqDatas = new List<LinqData>(); 14 linqDatas.Add(new LinqData() { Name = "zsgg", Score = "98", Age = 12 }); //这里使用了对象初始化器 15 linqDatas.Add(new LinqData() { Name = "lsb", Score = "85", Age = 15 }); 16 linqDatas.Add(new LinqData() { Name = "ww", Score = "87", Age = 15 }); 17 linqDatas.Add(new LinqData() { Name = "zd", Score = "85", Age = 18 }); 18 int lastIndex=linqDatas.LastIndexOf(dataForTest); 19 Console.WriteLine(lastIndex); 20 } 21 22 } 23 24 public class LinqData 25 { 26 public string Name { get; set; } 27 public string Score { get; set; } 28 public int Age { get; set; } 29 30 } 31 32 33 } 34
original code
在18行用List<T>类内置的LastIndexOf方法来求取对象的下标时发现其下标一直为-1(即未在linqDatas集合中找到dataForTest对象),可是该集合中明明包含dataForTest对象的,这是为什么呢?
经过群里好友的提醒我明白了,原来是LastIndexOf方法内置的比较逻辑无法判别出两个LinqData对象是相等的,故而无法找到dataForTest对象,所以返回-1。那么该怎么办呢?我的想法是对LastIndexOf方法进行扩展。故而有了以下的代码:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 namespace DemoLinq 7 { 8 class Program 9 { 10 public static LinqData dataForTest = new LinqData { Name = "lsb", Score = "85", Age = 15 }; 11 static void Main(string[] args) 12 { 13 14 List<LinqData> linqDatas = new List<LinqData>(); 15 linqDatas.Add(new LinqData() { Name = "zsgg", Score = "98", Age = 12 }); //这里使用了对象初始化器 16 linqDatas.Add(new LinqData() { Name = "lsb", Score = "85", Age = 15 }); 17 linqDatas.Add(new LinqData() { Name = "ww", Score = "87", Age = 15 }); 18 linqDatas.Add(new LinqData() { Name = "zd", Score = "85", Age = 18 }); 19 int lastIndex=linqDatas.LastIndexOf(dataForTest); 20 Console.WriteLine(lastIndex); 21 } 22 23 24 } 25 26 public class LinqData:IEquatable<LinqData> //自定义类需实现IEquatable<T>接口 27 { 28 public string Name { get; set; } 29 public string Score { get; set; } 30 public int Age { get; set; } 31 32 public bool Equals(LinqData other) 33 { 34 return Name.Equals(other.Name) && Score.Equals(other.Score) && Age.Equals(other.Age); 35 } 36 } 37 38 39 40 public static class Extend 41 { 42 43 public static int MyLastIndexOf<TSource>(this IEnumerable<TSource> source, TSource item) where TSource:IEquatable<TSource> 44 { 45 List<TSource> data = source.ToList(); 46 int index = -1; 47 foreach (TSource t in data) 48 { 49 if (t.Equals(item)) 50 { 51 index = data.Count - 1 - data.IndexOf(t); 52 } 53 } 54 return index; 55 } 56 57 58 } 59 } 60
new code
主要思路如下:
- 自定义类实现IEquatable<T>接口(即实现Equals方法来定义判等规则)
- 编写扩展方法MyLastIndexOf(注意扩展方法的参数,在这里为this IEnumerable<TSource> source与TSource item)
- 对扩展方法添加泛型约束(where TSource:IEquatable<TSource>)
时间: 2024-09-28 06:32:26