如何在C#中使用Linq查找最新员工薪水?

时间:2019-10-17 16:15:18

标签: c# linq

在解决c#问题时,我在网上遇到了一个具有挑战性的问题,要使用SQL查找这个问题很容易,但是使用LINQ对我来说似乎很困难。 这是input.txt文件中的数据。

e.target.className = "active"

输出为: 工程:600000 测试:350000

请仅在processData函数中进行更改。感谢您的帮助。

22, Rajan Anand, Engineering, 1600000
23, Swati Patil, Testing, 800000
27, Vijay Chawda, Engineering, 800000
29, Basant Mahapatra, Engineering, 600000
32, Ajay Patel, Testing, 350000
34, Swaraj Birla, Testing, 350000

2 个答案:

答案 0 :(得分:4)

return lines
  .Select(l=>l.Split(','))
  .GroupBy(i=>i[2])
  .ToDictionary(
    k=>k.Key, 
    v=>int.Parse(v.OrderByDescending(z=>int.Parse(z[0])).First()[3]));

或更可读:

return lines
  .Select(l=>l.Split(','))
  .Select(z=>new {Id=int.Parse(z[0]), Name=z[1], Department=z[2], Salary=int.Parse(z[3])})
  .GroupBy(e=>e.Department)
  .ToDictionary(k=>k.Key,v=>v.OrderByDescending(z=>z.Id).First().Salary);

答案 1 :(得分:1)

您可以尝试使用processData函数中的以下代码,获得输出:

Dictionary<String, int> retVal = new Dictionary<String, int>();

Dictionary<int, string> empWithDepart = lines.Select(x => x.Split(',')).ToDictionary(x => Convert.ToInt32(x[0]), x => Convert.ToString(x[2]));
Dictionary<int, int> empWithSalary = lines.Select(x => x.Split(',')).ToDictionary(x => Convert.ToInt32(x[0]), x => Convert.ToInt32(x[3]));
var departWithHighestEmpID = empWithDepart.OrderByDescending(x => x.Key).GroupBy(x => x.Value)
                               .ToDictionary(x => x.Key, x => x.FirstOrDefault().Key).ToList();
departWithHighestEmpID.Sort((pair1, pair2) => pair1.Key.CompareTo(pair2.Key));
foreach (var item in departWithHighestEmpID)
{
    retVal.Add(item.Key, empWithSalary[item.Value]);
}

return retVal;