简体   繁体   English

更新IList <T> 从另一个IList <T>

[英]Update IList<T> from another IList<T>

I have two ILists. 我有两个ILists。

users of type IList<CustomClassOne> and IList<CustomClassOne>类型的用户,以及

contacts of type IList<CustomClassTwo> . IList<CustomClassTwo>类型的联系人。

Both classes have a unique ID. 这两个类都有唯一的ID。 I need fill CustomClassOne's property "Description" by using CustomClassTwo's property "Info". 我需要使用CustomClassTwo的属性“ Info”来填充CustomClassOne的属性“ Description”。

foreach (CustomClassOne user in users )
{
    if (!string.IsNullOrEmpty(user.Description))
    {
        long id = user.ID;
        string desc = user.Description;

        var temp =  contacts.Select(p => p.ID = id);
        ...
        ...
    }
    else
        continue;

}

It sounds like you need to use a Join : 听起来您需要使用Join

foreach (var pair in users.Join(contacts, u => u.ID, c => c.ID, Tuple.Create))
{
    pair.Item1.Description = pair.Item2.Info;
}

Or if you prefer query syntax : 或者,如果您更喜欢查询语法

var pairs = 
    from user in users 
    join contact in contacts on user.ID equals contact.ID
    select new { user, contact };
foreach (var pair in pairs)
{
    pair.user.Description = pair.contact.Info;
}

You can use a Join to match up the two types together, after which you can iterate the matches and apply the changes. 您可以使用Join将两种类型匹配在一起,然后可以迭代匹配并应用更改。

var query = from contact in contacts
    join user in users
    on contact.Id equals user.Id
    into users
    select new 
    {
        contact,
        users,
    }

foreach(var match in query)
    foreach(var user in match.users)
    {
        user.Description = match.contact.Info;
    }

You can make the search in a foreach loop and if found assign to the CustomClassOne instance: 您可以在foreach循环中进行搜索,如果找到,则将其分配给CustomClassOne实例:

foreach (CustomClassOne item in users)
{
     var temp = contacts.Find(c => c.ID == item.ID);
     item.Description = temp == null ? item.Description : temp.Info;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM