下面是我的格式,其中存储了我的对象数据。我是linq的新手。
Server1, Database, MySQL, 5.5
Server2, Database, MySQL, 5.1
Server3, OS, Ubuntu, 10.04
Server1, OS, Ubuntu, 10.04
Server2, OS, Ubuntu, 12.04
Server3, Language, Python, 2.6.3
以下是我的班级结构。
public class dettails
{
public string server { get; set; }
public string details1 { get; set; }
public string details2 { get; set; }
public string version { get; set; }
public dettails(string Server, string Details1, string Details2, string Version)
{
server = Server;
details1 = Details1;
details2 = Details2;
version = Version;
}
}
下面是在我的对象列表中添加数据的代码。
List<dettails> objEmps = new List<dettails>();
while ((line = sr.ReadLine()) != null)
{
objEmps.Add(new dettails(fields[0].ToString().Trim(), fields[1].ToString().Trim(), fields[2].ToString().Trim(), fields[3].ToString().Trim()));
}
我想使用linq输出如下所示。
在至少2个不同的服务器上安装了过时版本(即非最新版本的版本)的软件包名称列表。
因此,在这种情况下,程序的输出应为:
Ubuntu的 因为Ubuntu 10.04是一个过时的版本(最新版本是12.04),它安装在两个服务器上(服务器3和服务器1)。
我如何使用linq实现它。请建议
答案 0 :(得分:1)
这是一些LINQ,发现Ubuntu已经过时了。如果您在输出要输出的问题时需要完整的解释,那将会有更多的工作。
var detailList = new List<dettails>()
{
new dettails("Server1", "Database", "MySQL", "5.5"),
new dettails("Server2", "Database", "MySQL", "5.1"),
new dettails("Server3", "OS", "Ubuntu", "10.04"),
new dettails("Server1", "OS", "Ubuntu", "10.04"),
new dettails("Server2", "OS", "Ubuntu", "12.04"),
new dettails("Server3", "Language", "Python", "2.6.3")
};
// 2. group details into software
var softwareGrouping = detailList.GroupBy(d => new {d.details1, d.details2});
// find software matching criteria
var obsoleteSoftware = softwareGrouping.Where(sg => sg
// first split into versions
.GroupBy(z => z.version)
// sort version groups by the version number (oversimplified method)
.OrderByDescending(z => z.Key)
// ignore latest version
.Skip(1)
// get versions where installation count is greater than 1
.Where(ss => ss.Count() > 1)
// return if there are any old versions found
.Any()
);
// 3. now create a result object for each found version
var results = obsoleteSoftware.Select(y => y.Key);
/* A more condensed version
var results = detailList.GroupBy(x => new {x.details1, x.details2})
.Where(y => y.GroupBy(z => z.version).OrderByDescending(z => z.Key).Skip(1).Where(ss => ss.Count() > 1).Any())
.Select(y => y.Key);
*/
foreach(var res in results)
{
Console.WriteLine("{0}, {1}", res.details1, res.details2);
}