2

In C# 7 we have value tuples of the form (a, b, c, ...) and deconstruction of them (via var (a, b, c, ...) = (a, b, c, ...)).

I have a tuple of the form (row: <int>, column: <int>), and I want to create a new tuple of the form (row: <int>, column: <int>, content: <char>) using the previous one.

In Python I can do:

existing = [1, 2]
new = [*existing, 3]

Or with dicts:

existing = {'row':1, 'column':2}
new = {**existing, 'content':'1'}

Is there a similar pattern in C#?

I can of course deconstruct the tuple into variables, then recombine them:

var (row, column) = (row: 1, column: 2);
var result = (row, column, content: '1');

However the actual situation is more complex. I have a function that returns the existing tuple, and an one-line function that constructs the new. If I simplify this it will be like:

private (int row, int column) ExistingTuple() => (row: 1, column: 2);

private (int row, int column, char content) NewTuple() => (/* What should I do here */ExistingTuple(), content: '1');

For the simplicity and the readability, I want it as an arrow function (T F() => E;). If I would implement my suggestion, it will be seem like:

private (int row, int column, char content) NewTuple()
{
    var (row, column) = ExistingTuple();
    return (row, column, content: '1');
}

Is there a more elegant way to do that?

4

2 回答 2

3

您可以将其编写为扩展方法,尽管听起来可能不像您想要的那样简洁:

public static (T1, T2, T3) TupleAppend<T1, T2, T3>(
   this (T1, T2) me,
   T3 value
) =>
   (me.Item1, me.Item2, value);

用作:

var triple = (1, 2).TupleAppend(3);

您还需要每个尺寸的重载,如果您想一次添加多个新项目,甚至需要更多重载。

于 2019-12-08T07:41:57.823 回答
1

从设计的角度来看,这可能是两种不同的数据类型。元组是实际数据的(row, col)索引。因此,您可以使用嵌套元组来表达此意图:

private ((int row, int column), char content) EnrichedTuple() => 
    (ExistingTuple(), content: '1');
于 2019-12-08T08:12:22.297 回答