如何在 C# 中使用 linq 读取列表中的列表项?

  • 本文关键字:列表 读取 linq c# list linq
  • 更新时间 :
  • 英文 :


>我有以下类

[Serializable]
[DataContract]
public class R_ButterFly_Collection
{
[DataMember]
public Int64? CollectionNameID { get; set; }
[DataMember]
public string CollectionName { get; set; }
}

我需要阅读CollectionNameIDCollectionName给定的匹配collection_name.

这就是我尝试CollectionName的方式:

string CollectionName = ButterFlyList.Where(x => x.CollectionName == butterflyName)

但是我需要CollectionNameIDCollectionName,我该怎么做?

这就是我想要的:

Int64 CollectionNameID, CollectionName = ButterFlyList.Where(x => x.CollectionName == butterflyName)

您可以使用:

List<R_ButterFly_Collection> results = ButterFlyList.Where(x => x.CollectionName == butterflyName).ToList();

假设:

var ButterFlyList = new List<R_ButterFly_Collection>()
{
new R_ButterFly_Collection()
{
CollectionName="one",
CollectionNameID=1
},
new R_ButterFly_Collection()
{
CollectionName="two",
CollectionNameID=2
},
new R_ButterFly_Collection()
{
CollectionName="three",
CollectionNameID=3
}
};

然后你可以使用 linq 并返回元组结果:

var results = ButterFlyList.Where(x => x.CollectionName == "one").Select(p => new Tuple<long, string>(p.CollectionNameID ?? 0, p.CollectionName));

请注意,您需要为"集合名称 ID"字段处理可为空的长整型。

最新更新