简体   繁体   中英

Add only item as a List

class Nameday
{
    public class Date
    {
        public int mm;
        public int dd;

        public Date(int get_mm, int get_dd)
        {
            mm = get_mm;
            dd = get_dd;
        }
    }

Dictionary<string, List<Date>> name_day = new Dictionary<string, List<Date>>();

To be able to to add a new value i have to define a List like this:

List<Date> tmp = new List<Date>();
tmp.Add(new Date(10, 14));
name_day.Add(item, tmp);

It works fine but i would like to leave the "tmp" part to something like this:

name_day.Add(item, new Date(mm,dd).ToList()); 

Can i do it?

There are two solutions I see to make a oneliner solution similar to the one you expect:

  1. Without additional code, you can instantiate directly the List with its item.

     name_day.Add(item, new List<Date>{new Date(mm,dd)});
  2. Or you can implement a ToList method in Date ...but it's rather useless

    public List<Date> ToList() => new List<Date> { this };

    then as you expected

    name_day.Add(item, new Date(mm,dd).ToList());

    EDIT a better solution is using a method extension as described in weichch's answer

  3. Another way is using an extension method on the Dictionary

    public static class DictionaryExtensions { public static void Add(this Dictionary<string, List<Date>> dict,string key, Date date) { dict.Add(key, new List<Date>{ date }); } } //...and then use it that way name_day.Add(item, new Date(mm,dd)

    ...and you can also add code to check if there is already a list corresponding to the same key and add it....

See comments under this answer for reason why extension method :)

You can create an extension method:

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods

public static class DataExtensions
{
    public static List<Date> ToList(this Date date)
    {
        return new List<Date> { date };
    }
}

Then you can do:

name_day.Add(item, new Date(mm,dd).ToList()); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM