开发者

how to get Dictionary<int , ClassA> from Regex.Split

I have a classA that has some public properties & overrides TosString method to to concatenate strings in these properties. It also has a property that returns int key;

I am using

string str = value1 + value2 + value3; 

each value has # separated properties of classA

string[] values = Regex.Split(str,'#');

foreach(classA value in values)
{
    dictionary.add(value.key, value);
}

This works fine

=====================================================================

For this scenario I want to use

values.ToDictionary

Can any one sugge开发者_如何学Cst how to use this?


It sounds like you want something along the lines of:

Regex.Split(str,'#')
.Select(s => new ClassA(s))
.ToDictionary(value => value.Key);

This will take each string that gets returned from Split, convert it to a ClassA somehow (that part is missing from your question), and return a dictionary where the keys all come from the ClassA instances and the values are the instances themselves.


It occurs to me that you might really want is to get the properties from a class and turn them into key-value pairs in a dictionary.

If that's what you're looking to do then Class -> String -> Array -> Dictionary is taking the long way.

If that's the case maybe you want to try a more direct approach

Given a class like this

 class classA
    { 
        public string Name{get;set;}
        public string  website { get; set; }
        public string location { get; set; }
        public int age { get; set; }
        public int reputation { get; set; }

        private string somthingPrivate { get; set; }


    }

The following creates a dictionary variable named result.

classA test = new classA() { Name = "Jeff Atwood", website = "codinghorror.com/blog", location = "El Cerrito, CA", age = 40, reputation = 15653 };


var result = test.GetType().GetProperties().ToDictionary(property => property.Name,
                                                    property => property.GetValue(test,null),
                                                     StringComparer.OrdinalIgnoreCase);

foreach (var key in result.Keys)
    Console.WriteLine("{0} : {1}", key, result[key]);

And outputs this

Name : Jeff Atwood
website : codinghorror.com/blog
location : El Cerrito, CA
age : 40
reputation : 15653
Press any key to continue . . .
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜