gpt4 book ai didi

c# - 使用 LINQ 对备用对进行分组

转载 作者:可可西里 更新时间:2023-11-01 08:16:38 25 4
gpt4 key购买 nike

我正在尝试对 DTOs 的列表进行分组其中包含备用家庭对,以按照以下格式对它们进行分组,以尽量减少重复。

这是我目前拥有的 DTO 结构,如您所见,这些行也可以根据反向关系组合在一起。

+----------+------------+-----------+
| PersonId | RelativeId | Relation |
+----------+------------+-----------+
| 1 | 2 | "Son" |
| 2 | 1 | "Father" |
| 1 | 3 | "Mother" |
| 3 | 1 | "Son" |
| 2 | 3 | "Husband" |
| 3 | 2 | "Wife" |
+----------+------------+-----------+

像这样:

+----------+------------+-----------+-----------------+
| PersonId | RelativeId | Relation | ReverseRelation |
+----------+------------+-----------+-----------------+
| 1 | 2 | "Son" | "Father" |
| 1 | 3 | "Mother" | "Son" |
| 2 | 3 | "Husband" | "Wife" |
+----------+------------+-----------+-----------------+

我正在尝试的代码:

Program.cs

class Program
{
static void Main(string[] args)
{
List<RelationDTO> relationDTOList = new List<RelationDTO>
{
new RelationDTO { PersonId = 1, RelativeId = 2, Relation = "Son" },
new RelationDTO { PersonId = 2, RelativeId = 1, Relation = "Father" },

new RelationDTO { PersonId = 1, RelativeId = 3, Relation = "Mother" },
new RelationDTO { PersonId = 3, RelativeId = 1, Relation = "Son" },

new RelationDTO { PersonId = 2, RelativeId = 3, Relation = "Husband" },
new RelationDTO { PersonId = 3, RelativeId = 2, Relation = "Wife" },
};

var grp = relationDTOList.GroupBy(x => new { x.PersonId }).ToList();
}
}

RelationDTO.cs

public class RelationDTO
{
public int PersonId { get; set; }
public int RelativeId { get; set; }
public string Relation { get; set; }
}

Relations.cs

public class Relations
{
public int PersonId { get; set; }
public int RelativeId { get; set; }
public string Relation { get; set; }
public string ReverseRelation { get; set; }
}

最佳答案

你可以使用像这样的连接操作

var result = relationDTOList
.Where(v => v.PersonId < v.RelativeId)
.Join(
relationDTOList.Where(v => v.PersonId > v.RelativeId),
v => new Key{PersonId = v.PersonId, RelativeId = v.RelativeId},
v => new Key{PersonId = v.RelativeId, RelativeId = v.PersonId},
(p, q) => new Relations
{
PersonId = p.PersonId,
RelativeId = p.RelativeId,
Relation = p.Relation,
ReverseRelation = q.Relation
}
);

是:

public struct Key
{
public int PersonId { get; set; }
public int RelativeId { get; set; }
}

关于c# - 使用 LINQ 对备用对进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54017857/

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