简体   繁体   中英

Using C# Lambda to split string and search value

I have a string with the following value:

0:12211,90:33221,23:09011

In each pair, the first value (before the : (colon)) is an employee id, the second value after is a payroll id.

So If I want to get the payroll id for employee id 23 right now I have to do:

var arrayValues=mystring.split(',');

and then for each arrayValues do the same:

var employeeData = arrayValue.split(':');

That way I will get the key and the value.

Is there a way to get the Payroll ID by a given employee id using lambda?

If the employeeId is not in the string then by default it should return the payrollid for employeeid 0 zero.

You can try something like that

"0:12211,90:33221,23:09011"
            .Split(new char[] { ',' })
            .Select(c => {
                var pair = c.Split(new char[] { ':' });
                return new KeyValuePair<string, string>(pair[0], pair[1]);
            })
            .ToList();

You have to be aware of validations of data

If I were you, I'd use a dictionary. Especially if you're going to do more than one lookup.

Dictionary<int, int> employeeIDToPayrollID = "0:12211,90:33221,23:09011"
    .Split(',') //Split on comma into ["0:12211", "90:33221", "23:09011"]
    .Select(x => x.Split(':')) //Split each string on colon into [ ["0", "12211"]... ]
    .ToDictionary(int.Parse(x => x[0]), int.Parse(x => x[1]))

and now, you just have to write employeeIDtoPayrollID[0] to get 12211 back. Notice that int.Parse will throw an exception if your IDs aren't integers. You can remove those calls if you want to have a Dictionary<string, string> .

Using a Linq pipeline and anonymous objects:

"0:12211,90:33221,23:09011"
.Split(',')
.Select(x => x.Split(':'))
.Select(x => new { employeeId = x[0], payrollId = x[1] })
.Where(x=> x.employeeId == "23")

Results in this:

{
  employeeId = "23",
  payrollId = "09011"
}

These three lines represent your data processing and projection logic:

.Split(',')
.Select(x => x.Split(':'))
.Select(x => new { employeeId = x[0], payrollId = x[1] })

Then you can add any filtering logic with Where after this the second Select

You can use string.Split along with string.Substring .

var result = 
      str.Split(',')
         .Where(s => s.Substring(0,s.IndexOf(":",StringComparison.Ordinal)) == "23")
         .Select(s => s.Substring(s.IndexOf(":",StringComparison.Ordinal) + 1))
         .FirstOrDefault();

if this logic will be used more than once then I'd put it to a method:

public string GetPayrollIdByEmployeeId(string source, string employeeId){
    return  source.Split(',')
          .Where(s => s.Substring(0, s.IndexOf(":", StringComparison.Ordinal)) == employeeId)
          .Select(s => s.Substring(s.IndexOf(":", StringComparison.Ordinal) + 1))
          .FirstOrDefault();
}

Assuming you have more than three pairs in the string (how long is that string, anyway?) you can convert it to a Dictionary and use that going forward.

First, split on the comma and then on the colon and put in a Dictionary :

var empInfo = src.Split(',').Select(p => p.Split(':')).ToDictionary(pa => pa[0], pa => pa[1]);

Now, you can write a function to lookup payroll IDs from employee IDs:

string LookupPayrollID(Dictionary<string, string> empInfo, string empID) => empInfo.TryGetValue(empID, out var prID) ? prID : empInfo["0"];

And you can call it to get the answer:

var emp23prid = LookupPayrollID(empInfo, "23");
var emp32prid = LookupPayrollID(empInfo, "32");

If you just have three employees in the string, creating a Dictionary is probably overkill and a simpler answer may be appropriate, such as searching the string.

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