如何将两个子列表的值复制到 C# 中的单个列表中?
How to copy value of two sub list into a single list in c#?
我有一个列表集合
List<List<int>> FS=new List<List<int>>()
我已将值添加到每个列表。现在我的 FS
看起来像 FS={{1,2,3},{5,7},{3}}
.
如何将前两个子列表的值组合成一个新列表?
我需要变得像 {1,2,3,5,7}
同时使用 GetRange
和 SelectMany
:
FS = FS.GetRange(0, 2).SelectMany(x => x).ToList();
GetRange
是从 List
中获取 N
(在你的例子中是 N = 2
)个元素。
{{1,2,3},{5,7},{3}} => {{1,2,3},{5,7}}
SelectMany
用于将List<List<int>>
压扁为List<int>
。
{{1,2,3},{5,7}} => {1,2,3,5,7}
如果您想合并所有三个列表并且 select 只合并不同的项目,您可以使用 distinct 进行合并。
FS.SelectMany(list => list).Distinct();
如果您只想合并前两个列表。那么你必须只过滤两个项目或selecting列表中的前2个项目然后做一个联合。
FS.Take(2).SelectMany(list => list).Distinct();
因为你想合并前两个Lists
,你可以使用Take
来获得前两个集合,然后你可以使用SelectMany
来线性收集集合。
FS.Take(2).SelectMany(e=>e);
要消除重复项,请使用 Distinct
FS.Take(2).SelectMany(e=>e).Distinct();
工作Demo
如果 FS
总是有 2 个或更多项目,请使用 List.AddRange()
:
FS[0].AddRange(FS[1]);
编辑
以上示例将编辑原始列表。如果您想要一个新列表,您应该创建一个新列表并使用 AddRange
向其添加值:
List<int> newList = new List<int>();
newList.AddRange(FS[0]);
newList.AddRange(FS[1]);
您需要在 List
中使用 'AddRange' 方法
List<int> combinedList = new List<int>(FS[0]);
combinedList.AddRange(FS[1]);
我有一个列表集合
List<List<int>> FS=new List<List<int>>()
我已将值添加到每个列表。现在我的 FS
看起来像 FS={{1,2,3},{5,7},{3}}
.
如何将前两个子列表的值组合成一个新列表?
我需要变得像 {1,2,3,5,7}
同时使用 GetRange
和 SelectMany
:
FS = FS.GetRange(0, 2).SelectMany(x => x).ToList();
GetRange
是从 List
中获取 N
(在你的例子中是 N = 2
)个元素。
{{1,2,3},{5,7},{3}} => {{1,2,3},{5,7}}
SelectMany
用于将List<List<int>>
压扁为List<int>
。
{{1,2,3},{5,7}} => {1,2,3,5,7}
如果您想合并所有三个列表并且 select 只合并不同的项目,您可以使用 distinct 进行合并。
FS.SelectMany(list => list).Distinct();
如果您只想合并前两个列表。那么你必须只过滤两个项目或selecting列表中的前2个项目然后做一个联合。
FS.Take(2).SelectMany(list => list).Distinct();
因为你想合并前两个Lists
,你可以使用Take
来获得前两个集合,然后你可以使用SelectMany
来线性收集集合。
FS.Take(2).SelectMany(e=>e);
要消除重复项,请使用 Distinct
FS.Take(2).SelectMany(e=>e).Distinct();
工作Demo
如果 FS
总是有 2 个或更多项目,请使用 List.AddRange()
:
FS[0].AddRange(FS[1]);
编辑
以上示例将编辑原始列表。如果您想要一个新列表,您应该创建一个新列表并使用 AddRange
向其添加值:
List<int> newList = new List<int>();
newList.AddRange(FS[0]);
newList.AddRange(FS[1]);
您需要在 List
中使用 'AddRange' 方法List<int> combinedList = new List<int>(FS[0]);
combinedList.AddRange(FS[1]);