In the most of the case, we can use the LINQ to filter out a list of the object collection. But if we are designing a framework which means we will use the interface talk to each other. The collection has to be the container of a set of interface which will need some tricks to finish this job.
The interface is like this(As a quick example, I will create an extreme simple interface :))
1: public interface IName
2: {
3: string FirstName{get;set;}
4: string LastName { get; set; }
5: string Prefix { get; set; }
6: }
The implementation of this interface is
1: public class Name : IName
2: {
3: #region IName Members
4:
5: public string FirstName
6: {
7: get;
8: set;
9: }
10:
11: public string LastName
12: {
13: get;
14: set;
15: }
16:
17: public string Prefix
18: {
19: get;
20: set;
21: }
22:
23: #endregion
24: }
First, We will create a helper function to get a list of the names.
1: private List<IName> GetNames()
3: List<IName> list = new List<IName>();
At the very beginning, the LINQ code will be written like this
List<IName> MenList = (from men in list
where men.Prefix == "Mr"
select
(new Name { FirstName = men.FirstName, LastName = men.LastName, Prefix = men.Prefix })
).ToList();
But you will get the compiler error like this
Error 1 Cannot implicitly convert type 'System.Collections.Generic.List<LinqToInterface.Name>' to 'System.Collections.Generic.List<LinqToInterface.IName>' C:\Learning\Linq\LinqToInterface\LinqToInterface\Form1.cs 27 18 LinqToInterface
In this case, the compiler does not know that the Name is an implementation of the interface IName, so we need to use some other ways around.The way I can help to change the code to this
1: List<IName> list = GetNames();
2:
3: List<IName> MenList = (from men in list
4: where men.Prefix == "Mr"
5: select (IName)
6: (new Name { FirstName = men.FirstName, LastName = men.LastName, Prefix = men.Prefix })
7: ).ToList();
I hope this will help you when you need it.
del.icio.us Tags:
LINQ C#