使用VB.NET linq中的值列表填充checkboxlist

时间:2016-12-09 01:35:39

标签: c# asp.net vb.net linq webforms

我有一个值列表,例如:

Dim segments = New List(Of Segment) 
segments.Add(new Segmento() With {.Id= 1, .Name = "Segment 1" })
segments.Add(new Segmento() With {.Id = 2, .Name = "Segment 2" })
segments.Add(new Segmento() With {.Id = 3, .Name = "Segment 3" })

Dim selectedSegments = New List(Of  Integer) From {1,2}

CblSegments.DataSource = segments
CblSegments.DataValueField = "Id"
CblSegments.DataTextField = "Name"
CblSegments.DataBind()

现在,我必须在Vb .net中使用linq选择带有selectedSegments值的CblSegments清单中的项目。

任何人都可以提供帮助? 感谢。

2 个答案:

答案 0 :(得分:0)

您不需要2 For Each个循环来完成此任务,您可以这样做:

Dim CblSegments As New CheckBoxList

Dim segments = New List(Of Segmento)
segments.Add(New Segmento() With {.Id = 1, .Name = "Segment 1"})
segments.Add(New Segmento() With {.Id = 2, .Name = "Segment 2"})
segments.Add(New Segmento() With {.Id = 3, .Name = "Segment 3"})

Dim selectedSegments = New List(Of Integer) From {1, 2}    
CblSegments.DataSource = segments
CblSegments.DataValueField = "Id"
CblSegments.DataTextField = "Name"
CblSegments.DataBind()

For Each cblItem As ListItem In CblSegments.Items
    If selectedSegments.Contains(cblItem.Value) Then
        cblItem.Selected = True
    End If
Next

答案 1 :(得分:0)

对于C#:

private class servicetimeofday
{
public int servicetimeofdayid { get; set; }
public int serviceid { get; set; }
public int timeofdayid { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
List<servicetimeofday> servicetimesofday = new List<servicetimeofday>
{
new servicetimeofday() { servicetimeofdayid = 1, serviceid = 1, timeofdayid = 1 },
new servicetimeofday() { servicetimeofdayid = 2, serviceid = 1, timeofdayid = 2 },
new servicetimeofday() { servicetimeofdayid = 3, serviceid = 2, timeofdayid = 1 },
new servicetimeofday() { servicetimeofdayid = 4, serviceid = 2, timeofdayid = 3 }
};

var itemstocheck = from s in servicetimesofday
where s.serviceid == 2
select s.servicetimeofdayid;

(from i in CheckBoxList2.Items.Cast<ListItem>() 
where itemstocheck.Contains(Convert.ToInt32(i.Value))
select i).ToList().ForEach(i => i.Selected = true);
}