linq确定是否在list <class> </class> </string>中选择字段时找到list <string>中的字段名称

时间:2013-09-17 17:51:00

标签: c# linq

我有一个类列表和一个字符串列表。字符串列表包含与类中的字段匹配的字段名称。是否有Linq查询可以确定两个列表之间的共同字段是什么?请参阅下面的示例。

public class ClassA
{
    public string Field1{get; set;}
    public decimal Field2{get; set;}
    public int Field3{get; set;}

    public ClassA(string field1, decimal field2, int field3)
    {
        Field1 = field1;
        Field2 = field2;
        Field3 = field3;
    }
}

public void Main()
{
    List<ClassA> lstClass = new List<ClassA>();
    lstClass.Add(new ClassA("value1", 1.23, 1));
    lstClass.Add(new ClassA("value2", 0.32, 3));
    lstClass.Add(new ClassA("value3", 2.34, 9));

    List<string> lstNames = "Field1,Field2".ToString().Split(',').ToList();

    // How to find intersection using linq of lstClass and lstNames (should be list  containing Field1 and Field2).
}

第二个后续问题是如何从lstClass获取字段列表(应该是包含“Field1”,“Field2”和“Field3”的字符串列表。)

谢谢,

2 个答案:

答案 0 :(得分:3)

使用Reflection

    typeof(ClassA).GetProperties(
       BindingFlags.Public | BindingFlags.Instance)
    .ToList() // Returns all the public instance properties of ClassA

所以你的解决方案:

var lstFieldNames = typeof(ClassA).GetProperties(
       BindingFlags.Public | BindingFlags.Instance)
       .Select(p=>p.Name).ToList()

var intersect = lstFieldName.Intersect(lstNames);

答案 1 :(得分:0)

获取交集的值:

var lstFieldNames = typeof(ClassA).GetProperties(
       BindingFlags.Public | BindingFlags.Instance)
       .Select(p=>p.Name).ToList()

var intersect = lstFieldName.Intersect(lstNames);
var type = typeof(ClassA);
var myObject = new ClassA(); // or any other object you want its properties values
var values = intersect.Select(p => new {
           Name = p,
           Value = type
                  .GetProperty(p, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public)
                  .GetValue(myObject, null)
           });