gpt4 book ai didi

c# - 创建一个字典,键代表列表中的元素

转载 作者:行者123 更新时间:2023-12-03 23:11:54 25 4
gpt4 key购买 nike

我想创建一个 Dictionary哪里Key s 代表来自 List 的元素.每个列表元素都必须出现在这个字典中。

例子:
一部电影有一个 Actor 名单。

现在我想要一个 Actor 出演的电影列表。如果电影有多个 Actor ,每个 Actor 都应该在自己的列表中列出这部电影。

我有这样的数据结构:

public class MovieData
{
public List<string> Actors { get; set;}
public string Title { get; set; }
public DateTime ReleaseDate { get; set; }
public string FilePath { get; set; }
}

一个小 示例 为了说明这一点:
var movie1 = new MovieData { 
Title = "Movie1",
Actors = new List<string> { "Bob Smith", "Alice Stevens"}};

var movie2 = new MovieData {
Title = "Movie2",
Actors = new List<string> { "Alice Stevens"}};

var movie3 = new MovieData {
Title = "Movie3",
Actors = new List<string> { "John Doe" }};

想要的 结果 应该是这样的:
Alice Stevens => { "Movie1", "Movie2" }
Bob Smith => { "Movie1" }
John Doe => { "Movie3" }

我想出了以下代码,但它只关注列表中的第一个参与者( FirstOrDefault() )。所以列表中的其他 Actor 被忽略。
var actorMovieList = movieDataList
.ToLookup(movie => movie
.Actors
.FirstOrDefault(), movie => movie);

我如何将其他 Actor 包括在列表中?我必须遍历 lambda 内部的 Actor 列表,但我不知道如何。

最佳答案

你可以试试SelectMany压平初始 List<List<string>>进入

{actor, title}

记录然后放 GroupByactor 将它们分组进入所需的字典:
var result = movieDataList
.SelectMany(movie => movie
.Actors
.Select(actor => new { // from now we have flat cursor of
actor = actor, // {actor, title} records
title = movie.Title
}))
.GroupBy(record => record.actor, // ... which we group by actor:
record => record.title) // actor and movies (s)he played in
.ToDictionary(group => group.Key, // or ToLookUp()
group => group.ToList());

关于c# - 创建一个字典,键代表列表中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60669238/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com