开发者

C# Can a dictionary<int, myobject> be converted into a list?

开发者 https://www.devze.com 2023-02-13 18:05 出处:网络
let\'s assume this is my custom object public class myObject { public int Id {get;set;} public string Name {get;set;}

let's assume this is my custom object

public class myObject
{
    public int Id {get;set;}
    public string Name {get;set;}
    public string Location {get;set;}
}

And I am returning a collection of m开发者_JAVA百科yObject instances in a dictionary:

return new Dictionary<int, List<MyObject>>(); 

This collection is basically a list of my objects. the key refers to the parent class's Id which has one to many relationship with myObject class.

What is the best way to create a list out of dictionary?

Instead of using Dictionary<int, List<MyObject>>, I am planning to use:

public class myObject
{
    public int Id {get;set;}
    public string Name {get;set;}
    public string Location {get;set;}
    public int ParentId {get;set;}**
}

and returning:

return new List<MyObject> myObjects(); 

what is your suggestion?


return myDict.Values.ToList();

You just need to get at the values, which is thankfully convenient.

EDIT:

Now that I understand a bit more of the problem, you want to set the Id field of each object to its key in the Dictionary (the parent id) before returning the list.

Well, first I would recommend that you simply set that property before adding it to the list in the first place. However, if you can't do that (for some unfathomable reason) you can simply iterate through the Dictionary beforehand and set the property:

foreach( var pair in dict )
{
    foreach( var myObj in pari.Value )
    {
        myObj.Id = pair.Key;
    }
}

return dict.Values.ToList();

Let me know if I'm missing something fundamental to your problem here.


This collection is basically a list of my objects. the key refers to the parent class's Id which has one to many relationship with myObject class.

The key in the dictionary should be unique, so how can you create a one to many relationship in such case ?

Anyway, you'll first have to create a new class which is able to hold all the existing values, and the extra parentId:

        public class MyObject2
        {
            public MyObject2(int id, string name, string location, int parentId)
            {
                this.Id = id;
                this.Name = name;
                this.Location = location;
                this.ParentId = parentId;
            }

            public int Id
            {
                get;
                set;
            }
            public string Name
            {
                get;
                set;
            }
            public string Location
            {
                get;
                set;
            }

            public int ParentId
            {
                get;
                set;
            }

            public override string ToString()
            {
                return String.Format ("Id={0}; Name={1}; Location={2}; ParentId={3}", Id, Name, Location, ParentId);
            }
        }

Then, with a simple LINQ query, you can achieve what you want:

var dict = new Dictionary<int, myObject> ();
dict.Add(2, new myObject(1, "Test1", "Somewhere"));
dict.Add (1, new myObject (2, "Test2", "location"));

var result = dict.Select (kp => new MyObject2 (kp.Value.Id, kp.Value.Name, kp.Value.Location, kp.Key)).ToList ();

 foreach( var r in result )
 {
     Console.WriteLine (r.ToString ());
 }

 Console.ReadLine ();


If you want the key to be the ParentId and the value to be all the instances of MyObject that have that parent, maybe a Dictionary isn't the best data structure. Maybe you want to use a Lookup, which is basically a Dictionary that can have multiple values for a single key. The (possible) downside being that a Lookup is read-only. You create it once, and then use it to, well, look things up. But you can't modify it later, only recreate it.

Given a list of all the instances of MyObject, you'd create a Lookup like this:

ILookup<int, MyObject> myLookup = allObjects.ToLookup(x => x.ParentId);

Edit:

I see from comments on another answer that you're actually starting with a Dictionary<int, List<MyObject>> (the moral equivalent of a Lookup) and you want to get a flattened list of all the instances of MyObject. This is actually an easy one-liner:

IEnumerable<MyObject> allObjects = dict.Values.SelectMany(x => x);


Do you want to put the keys or the values into the list?

For the keys, do:

return new List<int>(dict.Keys);

For the values (which I think is what you're looking for) do:

return new List<MyObject>(dict.Values);

If you want both, you can use a Tuple, but you have to be using .NET 4.0 or higher.

List<Tuple<int, MyObject>> list = new List<Tuple<int, MyObject>>();
foreach (var i in dict.Keys) {
    list.Add(Tuple.Create(i, dict[i]));
}
return list;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号