【发布时间】:2017-12-13 11:55:18
【问题描述】:
我有一个如下列表
我想把它转换成这样的列表
谁能推荐一些示例代码?
我试过下面的代码
class Program
{
static void Main(string[] args)
{
var mockForDataColection = Mock.MockForDataColection();
Factory f = new Factory();
List<ResultSet> rl = new List<ResultSet>();
var groups = mockForDataColection.GroupBy(x => new { group1 = x.GroupIdOne, group2 = x.GroupIdTwo, group3 = x.GroupIdThree }).ToList();
f.Name = mockForDataColection.FirstOrDefault(c => c.Key == "Chamber").Value;
f.RunNumber = mockForDataColection.FirstOrDefault(c => c.Key == "RunNumber").Value;
var groupBy = mockForDataColection.GroupBy(c => c.GroupIdThree).Skip(1);
foreach (var dataCollection in groupBy)
{
ResultSet r = new ResultSet();
r.BarCode = dataCollection.FirstOrDefault(d => d.Key == "BarCode").Value;
r.IsPassed = dataCollection.FirstOrDefault(d => d.Key == "IsPassed").Value;
rl.Add(r);
}
f.ResultSet = rl;
}
}
public class DataCollection
{
public int GroupIdOne { get; set; }
public int GroupIdTwo { get; set; }
public int GroupIdThree { get; set; }
public string Key { get; set; }
public string Value { get; set; }
}
public class Factory
{
public string Name { get; set; }
public string RunNumber { get; set; }
public List<ResultSet> ResultSet { get; set; }
}
public class ResultSet
{
public string BarCode { get; set; }
public string IsPassed { get; set; }
public int FailiureCode { get; set; }
}
public static class Mock
{
public static List<DataCollection> MockForDataColection()
{
List<DataCollection> dataCollectionList = new List<DataCollection>();
DataCollection dataCollection = new DataCollection
{
GroupIdOne = 1,
GroupIdTwo = 1,
GroupIdThree = 0,
Key = "Chamber",
Value = "Test Chamber"
};
DataCollection dataCollection1 = new DataCollection
{
GroupIdOne = 1,
GroupIdTwo = 1,
GroupIdThree = 0,
Key = "RunNumber",
Value = "2"
};
DataCollection dataCollection2 = new DataCollection
{
GroupIdOne = 1,
GroupIdTwo = 2,
GroupIdThree = 3,
Key = "IsPassed",
Value = "P"
};
DataCollection dataCollection3 = new DataCollection
{
GroupIdOne = 1,
GroupIdTwo = 2,
GroupIdThree = 3,
Key = "BarCode",
Value = "PQWERT"
};
DataCollection dataCollection4 = new DataCollection
{
GroupIdOne = 1,
GroupIdTwo = 2,
GroupIdThree = 4,
Key = "IsPassed",
Value = "F"
};
DataCollection dataCollection5 = new DataCollection
{
GroupIdOne = 1,
GroupIdTwo = 2,
GroupIdThree = 4,
Key = "BarCode",
Value = "IUTYY"
};
dataCollectionList.Add(dataCollection);
dataCollectionList.Add(dataCollection1);
dataCollectionList.Add(dataCollection2);
dataCollectionList.Add(dataCollection3);
dataCollectionList.Add(dataCollection4);
dataCollectionList.Add(dataCollection5);
return dataCollectionList;
}
}
我认为这不是一个好的代码。请提出其他一些简单的方法来实现这一目标。
需要将数据收集类转换为工厂类。在数据中,集合类具有 Key 和 Value 属性。键是工厂类中的一个属性值是值。根据 GroupId Only 我们将决定它是转到父类(Factory)还是子类(ResultSet)。
GroupId 一个值相同意味着它都在一个实体下。 GroupId 两个值不同表示它是一个相关实体。
【问题讨论】:
标签: c# .net entity-framework linq