我有两个清单
List<string[]> List1;
List<string[]> List2;
List1看起来像这样:
SECTION BEGINNING Value Ending Value
section2 31507976.71 0
section6 31643256.16 0
section8 32297021.88 0
section14 31643256.16 0
列表2:
SECTION Ending Value
section2 31406327.47
section8 33863875.36
section10 32674862.89
我想根据每个列表第一列的值将list2中的项添加到list1。 List1应如下所示:
SECTION BEGINNING Value Ending Value
section2 31507976.71 31406327.47
section6 31643256.16 0
section8 32297021.88 33863875.36
section14 31643256.16 0
这是我的代码:
public static void getList()
{
var list1 = new[]
{
new {Section = "section2", BeginningValue = 31507976.71, EndingValue=0},
new {Section = "section6", BeginningValue = 31643256.16, EndingValue=0},
new {Section = "section8", BeginningValue = 32297021.88, EndingValue=0},
new {Section = "section14", BeginningValue = 31643256.16, EndingValue=0},
};
var list2 = new[]
{
new {Section = "section2", EndingValue=31406327.47},
new {Section = "section8", EndingValue=33863875.36},
new {Section = "section10", EndingValue=32674862.89},
};
var result = list1.Concat(list2).OrderByDescending(x => x.EndingValue).GroupBy(g => x.Section).ToList();
foreach (var item in result)
Console.WriteLine(item.Section + "-" + item.BeginningValue + "-" + item.EndingValue);
}
答案 0 :(得分:3)
简单的linq方法
var result = list1.Select(x => new
{
Section = x.Section,
BeginningValue = x.BeginningValue,
EndingValue = list2.Any(y => y.Section == x.Section) ?
list2.First(y => y.Section == x.Section).EndingValue :
0
}).ToList();
答案 1 :(得分:0)
请使用以下功能修改getList
功能:
public static void getList()
{
var list1 = new[] {
new {Section = "section2", BeginningValue = 31507976.71, EndingValue=0},
new {Section = "section6", BeginningValue = 31643256.16, EndingValue=0},
new {Section = "section8", BeginningValue = 32297021.88, EndingValue=0},
new {Section = "section14", BeginningValue = 31643256.16, EndingValue=0},
};
var list2 = new[]{
new {Section = "section2", EndingValue=31406327.47},
new {Section = "section8", EndingValue=33863875.36},
new {Section = "section10", EndingValue=32674862.89},
};
var result = from Item1 in list1
join Item2 in list2
on Item1.Section equals Item2.Section into ps
from p in ps.DefaultIfEmpty()
select new
{
Section = Item1.Section,
BeginningValue = Item1.BeginningValue,
EndingValue = (p != null ? p.EndingValue : Item1.EndingValue)
};
foreach (var item in result)
Console.WriteLine(item.Section + "-" + item.BeginningValue + "-" + item.EndingValue);
}