任何正文都可以将以下嵌套的forloop转换为linq查询。
我有以下类定义。
public class MessageCodes
{
public string IdentityKey{ get; set; }
public Dictionary<string, string> LangCollection { get; set; }
public MessageCodes()
{
LangCollection = new Dictionary<string, string>();
}
}
上面的类中的IdentityKey是唯一的,LangCollection可以有多个键值。
说
MessageCodes newCode = new MessageCodes()
{
MessageCode = "10",
LangCollection = new Dictionary<string, string>()
{
{"en","Hello"},
{"de","dello"},
{"fr","fello"},
}
};
MessageCodes oldCode = new MessageCodes()
{
MessageCode = "10",
LangCollection = new Dictionary<string, string>()
{
{"en","fello"},
{"de","pello"},
{"fr","fello"},
}
};
以上是MessageCode实例的一个示例。
现在我收集了NewMessageCodes和OldMessageCodes。我需要比较它们 以下是嵌套forloop的问题,
foreach (MessageCodes newMessageCode in newDiffMsgCodeCollection)
{
foreach (MessageCodes oldMessageCode in oldDiffMsgCodeCollection)
{
if (newMessageCode.MessageCode == oldMessageCode.MessageCode)
{
MessageCodes msgCodes = new MessageCodes();
msgCodes.MessageCode = newMessageCode.MessageCode;
Dictionary<string, string> langCollection = new Dictionary<string, string>();
foreach (KeyValuePair<string, string> newLangNode in newMessageCode.LangCollection)
{
foreach (KeyValuePair<string, string> oldLangNode in oldMessageCode.LangCollection)
{
string newCode = newLangNode.Key.Trim().ToLower();
string oldCode = oldLangNode.Key.Trim().ToLower();
if (newCode == oldCode )
{
if (newLangNode.Value != oldLangNode.Value)
{
langCollection.Add(newCode, oldCode);
}
}
}
}
msgCodes.LangCollection = langCollection;
}
}
}
将上面的代码混乱转换为Linq查询或Lambda表达式。
答案 0 :(得分:1)
newDiffMsgCodeCollection.ForEach(pd => {
oldDiffMsgCodeCollection.ForEach(pds =>
{
if (pd.MessageCode == pds.MessageCode)
{
//business logic
}
});
});
答案 1 :(得分:0)
我认为这几乎是你想要的:
var messageCodesQuery =
from newMessageCode in newDiffMsgCodeCollection
from oldMessageCode in oldDiffMsgCodeCollection
where newMessageCode.MessageCode == oldMessageCode.MessageCode
select new MessageCodes()
{
MessageCode = newMessageCode.MessageCode,
LangCollection = (
from newLangNode in newMessageCode.LangCollection
from oldLangNode in oldMessageCode.LangCollection
let newCode = newLangNode.Key.Trim().ToLower()
let oldCode = oldLangNode.Key.Trim().ToLower()
where newCode == oldCode
where newLangNode.Value != oldLangNode.Value
select new { newCode, oldCode }
).ToDictionary(x => x.newCode, x => x.oldCode)
};
您现在需要确保对结果做些什么。