通过将一个列表与另一个列表进行比较来填充属性

时间:2020-07-28 11:09:12

标签: c# linq

我有以下两个课程:

public class Post {
    public Guid Id {get;set;}
    public string PostType {get;set;}
    public string Title {get;set;}
    public string Content {get;set;}

    public void SetPostType(Item item)
    {
        if (item.PostId == Id) {
            PostType = item.PostType
        }
    }
}

public class Item {
    public Guid PostId {get;set;}
    public string PostType {get;set;}
}

如果我有一个Posts列表和一个不同长度的Items列表,如何将Posts.PostType设置为Items.PostType,其中Post.Id == Item.PostId

3 个答案:

答案 0 :(得分:1)

try {
    const resp = await fetch( link );
    if( resp.status === 200 ) {
        const obj = await resp.json();
        const dateStr = obj.date; // string
        const date = new Date( dateStr );
        document.getElementById('Dateee').valueAsDate = date;
    }
}
catch( err ) {
    alert( "Error: " + err );
}

答案 1 :(得分:0)

使用以下内容:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication11
{
    class Program
    {
        static void Main(string[] args) 
        {
            List<Post> posts = new List<Post>();
            List<Item> items = new List<Item>();

            var joins = from p in posts
                        join i in items on p.Id equals i.PostId
                        select new { post = p, item = i };

            foreach (var j in joins)
            {
                j.post.PostType = j.item.PostType;
            }
        }
    }
    public class Post
    {
        public Guid Id { get; set; }
        public string PostType { get; set; }
        public string Title { get; set; }
        public string Content { get; set; }
    }

    public class Item
    {
        public Guid PostId { get; set; }
        public string PostType { get; set; }
    }
}

答案 2 :(得分:0)

不清楚:

  • 是否有Posts没有Item?是否有ID永远不会是商品中PostId的帖子?
  • Posts最多有一个Item吗?是否没有两个Items具有相同的PostId
  • 每个带有非空PostId的Item都引用现有的Post吗?

如果一个帖子可能有多个引用此帖子的项目,那么您要使用哪种PostType?

因此,我假设:每个Post都具有零个或一个引用此Item的{​​{1}}。如果没有Post引用此Item,则您不想更改Post的值,如果有一个Post.PostType引用此{{1 }}您想将Item的值分配给Post,

在这种情况下,您要查找并合并Item.PostType等于Post.PostType的{​​{1}}和Posts。您不必担心没有Items的{​​{1}}或没有Post.Id的{​​{1}}。用数据库术语来说:您想(内部)加入帖子和项目。

使用LINQ,可通过the overloads of Enumerable.Join之一来完成。您从两个序列中选择两个序列,从一个序列中选择主键,从另一个序列中选择外键,并在它们匹配时执行参数resultSelector中指定的操作:

Item.PostId

因此,现在您拥有一个由所有帖子组成的序列,每个帖子都具有引用该帖子的项目中的PostType。如果您有没有项目的帖子,则它们不在最终结果中。如果您的帖子中包含两项,则它们都将位于最终结果中。

更新PostType:

Posts