简体   繁体   中英

Linq or better approach to extract values from string[]

I have this input string and need to extract values of Uid, pwd and Dsn attributes... I am splitting the values using ; char and then replacing Uid ="" and that's how I am reading values for other attributes too...

String[] test = "Uid=test;Pwd=abc;dsn=xxx".split(';')

id = test[0].Replace("Uid=", "");
pwd = test[0].Replace("Pwd", "");
datasrc = test[0].Replace("Dsn", "");

Is there any better approach to extract values from string[] ?

I suggest using Dictionary<String, String> and, yes, Linq to materialize the initial string into it:

  string test = "Uid=test;Pwd=abc;dsn=xxx";

  Dictionary<string, string> dict = test
    .Split(';')
    .Select(item => item.Split('='))
    .ToDictionary(pair => pair[0], pair => pair[1], StringComparer.OrdinalIgnoreCase);

  ...

  var id = dict["Uid"];
  var pwd = dict["Pwd"];
  var datasrc = dict["Dsn"]; // please, notice that the name is case insensitive

You can project after splitting and then split on = character and pick the second index, but it would only work, if the string is guaranteed to be always in this format, then this should work for you:

var result = "Uid=test;Pwd=abc;dsn=xxx".Split(';')
                                       .Select(x=> x.Split('=')[1]);

Result:

在此处输入图片说明

See the working DEMO Fiddle

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