且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

比较C#中不同类型的列表

更新时间:2022-12-29 08:23:24

如果我理解正确,那么您想比较类型本身,而不是列表中的实例.

If I understood it right, you want to compare the type itself, not the instances inside that list.

您可以这样操作:

List<string> metadata = new List<string>();//string list
metadata.Add("itemname");
metadata.Add("soid");
metadata.Add("qty");
metadata.Add("yada");

var result = from str in metadata
             join prop in typeof(Input).GetProperties() on str equals prop.Name
             select str;

foreach (string prop in result)
{
    Console.WriteLine(prop);
}

现在,如果您有一个T个未知对象的列表,并且希望将每个对象与元数据进行匹配,请告诉我,我会为您提供帮助.

Now, if you have a List of T unknown objects and want to match each with the metadata, tell me and I'll help you.

编辑:when we get the common name between list<input> and string how will get the value of corresponding member of the class.now you return only common names r8..?

您可以这样做.假设您有以下两个类:

You could do it like this. Suppose you have these two classes:

public class Input
{
    public string soid { get; set; }

    public string itemname { get; set; }

    public int qty { get; set; }
}

public class Yada : Input
{
    public string yada { get; set; }
}

所以Input具有4个属性中的3个,而Yada类具有所有4个属性.

So Input has 3 of the 4 properties, and Yada class has all 4.

然后假设我们有一个对象列表:

Then suppose we have a list of objects:

List<Input> inputclass = new List<Input>();//inputclass list

inputclass.Add(new Input() { itemname = "test",soid="myId",qty=10 });
inputclass.Add(new Yada() { itemname = "test2",soid="myId2", yada = "woo",qty=20 });

您可以使用以下代码从对象中获取所有匹配的属性,包括它们的当前值:

You could get all the matching properties from the objects, including their current values, with this code:

var result = inputclass.Select(
                 input => (from str in metadata
                           join prop in input.GetType().GetProperties()
                           on str equals prop.Name
                           select new { Obj = input, Prop = str, Value = prop.GetValue(input, null) }))
                           .SelectMany(i => i)
                           .GroupBy(obj => obj.Obj);

foreach (var obj in result)
{
    Console.WriteLine(obj.Key);
    foreach (var prop in obj)
    {
        Console.WriteLine(prop.Prop + ":" + prop.Value);
    }
    Console.WriteLine();
 }

 Console.ReadKey();

这是我的输入内容:

仅需注意,使用GetValue时要小心:例如,您必须对其进行一些细微更改才能与Indexers一起使用.

Just on a note, be careful when using GetValue: you'll have to do slight changes for it to work with Indexers, for example.