如何在元组中设置值c# [英] How set value in tuple c#

查看:113
本文介绍了如何在元组中设置值c#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好。我有一个元组(考试元组< string,int> iTuple =新元组< string,int>(A,1))。

我想改变值如何iTuple.Item2 = 3。如何改变?谢谢所有

Hello all. i have a tuple (exam tuple<string,int> iTuple=new tuple<string,int>("A",1)).
I want to change value how iTuple.Item2=3. How change? Thanks all

推荐答案

A 元组<> 是不可变的。因此,如果要更改值,则必须创建一个新值:

A Tuple<> is immutable. So you have to create a new one if you want to change the value:
Tuple<string, int> iTuple = new Tuple<string, int>("A", 1);
iTuple = new Tuple<string, int>(iTuple.Item1, 3);


除了 ProgramFox [ ^ ],我建议阅读这篇非常有趣的文章: C#4 - 元组 [ ^ ]。 MSDN也很有用:元组类 [< a href =https://msdn.microsoft.com/en-us/library/system.tuple%28v=vs.110%29.aspxtarget =_ blanktitle =New Window> ^ ]



注意:元组非常有用,但您必须处理特定的数据类型,例如自定义类。您可以使用Linq查询将元组转换为自定义数据类型(类)。请参阅:在LINQ查询表达式中使用自己定义的类型 [ ^ ]



比方说,你有自定义类如下:

In addition to solution 1 by ProgramFox[^], i'd suggest to read this very interesting article: C# 4 - Tuples[^]. MSDN migh be helpful too: Tuple Class[^]

Note: Tuples are very useful, but you have to work on specific data type, for example custom class. You can "transform" tuple to custom data type (class) via using Linq query. See: Using your own defined type in a LINQ query expression[^]

Let's say, you have custom class as follow:
public class Whatever
{
    private string sProp = string.Empty;
    private int iVal = 0;

    public Whatever()
    {
    }

    public Whatever(string _Prop, int _Val)
    {
        sProp = _Prop;
        iVal = _Val;
    }

    public string Prop
    {
        get{ return sProp; }
        set{ sProp = value; }
    }
    public int Val
    {
        get{ return iVal; }
        set{ iVal = value; }
    }
}





现在,您要创建数据列表......并先更改元素:



Now, you want to create list of your data... and change first element:

//list of tuples
List<Tuple<string, int>> MyTuple = new List<Tuple<string, int>>()
        {
            new Tuple<string, int>("A", 1),
            new Tuple<string, int>("A", 10),
            new Tuple<string, int>("A", 100)
        };

//transform to custom class collection
List<Whatever> ClassCollectionFromTupple = (from mt in MyTuple
    select new Whatever
        {
            Prop = mt.Item1,
            Val = mt.Item2
        }).ToList();

//get specific element
Whatever wr = ClassCollectionFromTupple[0];
//change value
wr.Val = 3;





试试吧!祝你好运!



Try! And Good Luck!


这篇关于如何在元组中设置值c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆