如何在 C# 中设置 List<Class> 的属性

How to set properties of a List<Class> in C#

我有一个 class 定义如下:

[DataContract]
public class Response2
{
    [DataMember(Name = "done")]
    public bool done;
    [DataMember(Name = "records")]
    public List<Response3> r3entry;
}

[DataContract]
public class Response3
{
    [DataMember(Name = "Id")]
    public string strId { get; set; }
    [DataMember(Name = "Name")]
    public string strName { get; set; }
}

现在,我想做的是从另一个 class 中获取值并填充...像这样:

string propertyRequest2 = CreatePropertyRequest2();
Response2 propResponse2 = MakeRequest2(propertyRequest2, sfToken);

List<Response> listAllData = new List<Response>();

foreach (var responseEntry in propResponse2.r3entry)
{
    listAllData.Add(new Response() { strId = responseEntry.strId, strName = responseEntry.strName } );

    // NOTE .strId IS ALWAYS UNIQUE IN BOTH CLASSES
    // - I know this is NOT the right syntax... will fix later.
    Where listAllData.strId = responseEntry.strId
    {
        listAllData.property = propertyResponse2(.strId=responseEntry.strId).property
    }
}

我敢肯定(至少)代码的最后一点对大多数阅读本文的人来说是痛苦的,但我会修复它,这样它就不会那么糟糕了。我只是不知道解释是否清楚。以防万一我错了,这里的重点更像是这样:

// WE HAVE A LIST OF CLASSES WITH PROPERTIES
// ASSUME PROPERTIES ARE ID, ITEM, NAME
LIST1 = { ("1", "A", "APPLE"), ("2", "B", "BANANA"), ("3", "C", "COCONUT")}

// NOW WE HAVE ANOTHER LIST THAT HAS THE SAME ID BUT DIFF DATA
// ASSUME PROPERTIES ARE ID, COLOR
LIST2 = { ("1", "RED"), ("2", "YELLOW"), ("3", "BROWN) }

// AND THEN I WANT TO CREATE A NEW LIST WITH BOTH SETS OF DATA COMBINED
// ASSUME PROPERTIES ARE ID, ITEM, NAME, COLOR
LIST3 = { ("1", "A", "APPLE", "RED"), ("2", "B", "BANANA"), ("3", "C", "COCONUT", "BROWN") }

关于如何做到这一点有什么想法吗?

内部连接投影:

var list = from l1 in LIST1
    join l2 in LIST2 on l1.ID equals l2.ID
    select new {
        l1.ID,
        l1.Item,
        l1.Name,
        l2.Color
    }
    .ToList()

在不知道您的目标是什么的情况下,Zip 函数作用于两个列表并且 returns 这两个列表的乘积。您可以在这里阅读更多内容:

Zip on MSDN

但实际上,如果您有两个事物列表,可以说:

int[] numbers = { 1, 2, 3, 4 };
string[] words = { "one", "two", "three" };
// The following example concatenates corresponding elements of the
// two input sequences.
var numbersAndWords = numbers.Zip(words, (first, second) => first + " " + second);

所以在你的情况下可能是这样的:

Response2[] response2 = //some list
Response3[] response3= // some other list
var response2Andresponse3 = response2.Zip(response3, (res2,res3) => //something you want to do with them

这会将 response2 的第一个元素与 response3 的第一个元素配对,依此类推。我们还假设它们具有相同的长度,因此您没有不成对的属性。

您必须想出一种方法将其输出到您可能觉得有用的内容中,但您将有一个列表,其中它们逐个元素对应。