1

I am new in C# and would like to know if it's possible to create an array in C# like following:

rates[0]['logic_id'] = 12;
rates[0]['line_id'] = ""
rates[0]['rate'] = rateVal;
rates[0]['changed'] = isChanged;

rates[1]['logic_id'] = 13;
rates[1]['line_id'] = ""
rates[1]['rate'] = secvalue;
rates[1]['changed'] = isChanged;

Can I create rates array in C# with such values?

EDIT:

My goal is to send rates array to a specific Web API service that is running with PHP. They accept only array with abovementioned structure. That's why I want to achieve that.

FireFalcon
  • 831
  • 11
  • 23
  • 2
    That object notation doesn't exist in C#. Whats so bad about creating proper objects? – BradleyDotNET Nov 07 '14 at 18:07
  • 1
    Wouldn't you rather have it strongly typed and create a Rate object? – John Koerner Nov 07 '14 at 18:07
  • Are you trying to add any arbitrary key to each array element? If not, define a *type* and make an array of those types. Then use `rates[0].rate = rateVal;` etc. – Mike Christensen Nov 07 '14 at 18:08
  • 2
    types in C# exist for a reason... – akonsu Nov 07 '14 at 18:08
  • @MikeChristensen I am trying to add key for each array element. That is why I need that structure in C#. – FireFalcon Nov 07 '14 at 18:10
  • @Oraz - I would use Dave Zych's answer below. – Mike Christensen Nov 07 '14 at 18:10
  • 3
    This appears to be an [XY Problem](http://meta.stackexchange.com/a/66378/171858). You want to create an array to solve some problem, but the problem you haven't described. Unless you are *literally* using SO to understand collections (arrays, enumerables, etc) it would be in everyones best interest if we understood what you think an array would solve for. – Erik Philips Nov 07 '14 at 18:11
  • BTW there're some edge cases where dictionaries are prefered over strong types – Matías Fidemraizer Nov 07 '14 at 18:12
  • @MatíasFidemraizer why would anyone not use a strongly-typed dictionary? Your comment doesn't really make sense. – Erik Philips Nov 07 '14 at 18:13
  • @BradleyDotNET can you suggest how to create proper object similar to that? – FireFalcon Nov 07 '14 at 18:14
  • 1
    @Oraz you already have your answer below... – L.B Nov 07 '14 at 18:15
  • @Oraz [Dave Zych has a good example in an answer](http://stackoverflow.com/a/26807420/209259). – Erik Philips Nov 07 '14 at 18:15
  • @ErikPhilips Makes sense. Just imagine a DTO that's used to do simple evaluations in the REST layer... would you end creating a bunch of strongly-typed DTOs just for this? Or, would you prefer to evaluate if a DTO has a property or not using reflection when `IDictionar` has `ContainsKey`? There're few edge cases, and not everything is a strongly-typed world :D – Matías Fidemraizer Nov 07 '14 at 18:18
  • I create strongly typed backend and javascript objects. Serialization and Deserialization becomes simple to maintain and extend. Using [Magic Strings](http://en.wikipedia.org/wiki/Magic_number_(programming)) in a dictionary is a poor choice almost all of the time. – Erik Philips Nov 07 '14 at 18:21
  • @ErikPhilips A dictionary isn't a magic string... – Matías Fidemraizer Nov 07 '14 at 18:26
  • @MatíasFidemraizer the comparison is an Strongly-Typed Object `Person.Name` vs an `IDictionary` when deserializing it from JSON it would most likely be a string or int, both of which are *Magic Strings/Number*. – Erik Philips Nov 07 '14 at 18:32
  • @ErikPhilips What happens if we deserialize to `ExpandoObject`? Curiously is an implementation of `TDictionary` and you can even access properties as an actual type. Anyway, I don't see that *magic strings* anywhere in any case! Am I wrong if I feel you need to evolve and escape from the dogma? – Matías Fidemraizer Nov 07 '14 at 18:35
  • @ErikPhilips We could maintain a long discussion about this... My point of view is current state of programming and C# capabilities let us mix the best of many worlds: imperative and functional language, strong and dynamically-typed languages. If we use that advantages based on repeatable patterns that work, we can escape from strict rules of *everything must be a class* even in C#. And it's not lowering the quality of our code. – Matías Fidemraizer Nov 07 '14 at 18:39
  • @MatíasFidemraizer I don't use ExpandoObject. But it looks like serialization creates [Magic strings (example default implementation)](http://stackoverflow.com/questions/5156664/how-to-flatten-an-expandoobject-returned-via-jsonresult-in-asp-net-mvc) as `Key="some magic string"`. Whoa, who said *everything must be a class*? I've never stated that. I prefer compile-time-checking *most of the time*, because it exists and I can know before my code is deployed it works. – Erik Philips Nov 07 '14 at 18:41
  • @ErikPhilips Whoa! haha! Well, compile-time checking doesn't verify that your code works. You need unit/integration testing for this, and/or use design by contract paradigm (code contracts)!! – Matías Fidemraizer Nov 07 '14 at 19:07
  • @MatíasFidemraizer no need to use the [logical fallacy - red herring](http://en.wikipedia.org/wiki/Red_herring) here. – Erik Philips Nov 07 '14 at 19:55
  • @ErikPhilips No falacy there. I'm talking about the question did by the OP. In fact, I find **offensive** that you compare my thoughts to a falacy. Thanks. – Matías Fidemraizer Nov 07 '14 at 23:45
  • Thank everyone for their support and feedback. I appreciate that. – FireFalcon Nov 08 '14 at 05:10

4 Answers4

4

The best approach here would be to create a Rate class that is held in a List<Rate>().

public class Rate
{
    public int LogicId { get; set; }
    public string LineId { get; set; }
    public decimal Rate { get; set; }
    public bool IsChanged { get; set; }
}

public void Populate()
{
    var rates = new List<Rate>();

    var rate = new Rate();
    rate.LogicId = 12;
    rate.LineId = string.Empty;
    rate.Rate = 0;
    rate.IsChanged = true;

    rates.Add(rate);
}

To access the values, you can loop through them:

foreach(var rate in rates)
{
    //Do something with the object, like writing some values to the Console
    Console.WriteLine(rate.LogicId);
    Console.WriteLine(rate.Rate);
}
Dave Zych
  • 21,581
  • 7
  • 51
  • 66
  • 1
    `+1` - You should probably note how to access the values too. – Mike Christensen Nov 07 '14 at 18:12
  • @Dave Zych if send `rates' as a List to Web API, how can they separate the values. For example, get LogicID and LineID separately? – FireFalcon Nov 07 '14 at 18:23
  • @Oraz to send this to an API you'll have to serialize it in some way, i.e. convert it to XML (if the API accepts XML) or JSON (if it accepts JSON). JSON is the more common, and you can use the Newtonsoft.JSON library to convert the list to a json array. The code is similar to `string jsonForApi = json.Serialize(rates)`; – Dave Zych Nov 07 '14 at 18:43
  • @DaveZych I've added reference to `Newtonsof.Json` library, but I cannot find any `Serialize` method for `Json` that takes `List` as a parameter. Can you help please? I am dealing with Windows Service in VS 2010 with `.Net Framework 4.0`. – FireFalcon Nov 07 '14 at 20:23
  • I found it: `var json = Newtonsoft.Json.JsonConvert.SerializeObject(rates)` – FireFalcon Nov 08 '14 at 05:08
2

You could solve it using arrays, but it's someway outdated the approach.

My suggestion is that you should use a List<Dictionary<string, object>>:

var data = new List<Dictionary<string, object>>();

data.Add(new Dictionary<string, object>());

data[0].Add("rate", rateVal);

And later you can access it like JavaScript using dictionary's indexer:

var rate = data[0]["rate"];

Update

OP said:

My goal is to send rates array to a specific Web API service that is running with PHP. They accept only array with abovementioned structure. That's why I want to achieve that.

No problem. If you serialize that list of dictionaries using JSON.NET, you can produce a JSON which will contain an array of objects:

[{ "rate": 2 }, { "rate": 338 }]

Actually, .NET List<T> is serialized as a JSON array and a Dictionary<TKey, TValue> is serialized as a JSON object, or in other words, as an associative array.

Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206
  • I need to send an array `rates` to a specific Web API service built with PHP. So is it possible to make a List of Dictionaries and after convert them into JavaScript array and send it to that web service? – FireFalcon Nov 07 '14 at 18:12
  • @Oraz, that's a different question than what is posted. It may be best to solve this question first, then post a different question. – gunr2171 Nov 07 '14 at 18:13
  • @Oraz Add JSON.NET to your solution/project's and a simple `JsonConvert.Serialize` giving the whole list of dictionaries will produce the desired output. For example, I expect a JSON like this: `[{ "rate": 438, "otherProperty": "whatever" }, { "rate": 4101, "otherProperty": "whatever 2" }]` – Matías Fidemraizer Nov 07 '14 at 18:15
0

This can depend on your specific neeeds, mut maybe you just want a list of objects

first create a class:

class Rate
{
    public int LoginId { get; set; }
    public int? LineId { get; set; }
    public decimal RateValue { get; set; }
    public bool IsChanged { get; set; }
}

Then, in any method you want, just use:

List<Rate> Rates = new List<Rate>();
Rates.Add(new Rate() {LoginId = 1, LineId = null, RateValue = Rateval, IsChanged = false});
Rates.Add(new Rate() {LoginId = 13, LineId = null, RateValue = SecVal, IsChanged = false});

EDIT

My apologies for the terrible answer, edited to account for the errors

cpacheco
  • 186
  • 9
  • `-1` - This won't even compile. – Mike Christensen Nov 07 '14 at 18:17
  • This also has, what most would consider, bad practices that being public fields. – Erik Philips Nov 07 '14 at 18:18
  • @ErikPhilips - It *has no* public fields. It only has private fields, which is one of the big reasons it won't compile. – Mike Christensen Nov 07 '14 at 18:20
  • @MikeChristensen yes you are correct. I was looking at the example setting fields, didn't notice the missing access modifiers. – Erik Philips Nov 07 '14 at 18:23
  • In the future I'd recommend testing your code in the IDE before posting it, until you are *very, very* familiar with C#. – Mike Christensen Nov 07 '14 at 18:41
  • There's also a random ? in there, `public int? lineId`. cpacheco is right to question that, but wrong to use that method to question it. `public int lineId {get; set;} // Is that an int or a string?` would be more appropriate. And lineId should be a string, much like phone numbers and zip codes. Even if it only contains numbers, the leading zeroes may be relevant. And the format is more relevant than a < or > comparison. Also, ids may contain letters. – RoboticRenaissance Jul 01 '17 at 00:30
0
public struct Rate
        {
            public int LoginId ;
            public int LineId ;
            public double RateValue ;
            public bool IsChanged;
        }

        public static void makelist()
        {
             List<Rate> Rates = new List<Rate>();
             Rates.Add(new Rate() {LoginId = 1, LineId = null, RateValue = Rateval,IsChanged = false});
        }

This method will only hold data, and not hold methods like a class.

With the data types defined in the struct, memory usage stays low as its only purpose is to store data. This is a midway between a variable and a class.

Alan P
  • 41
  • 8