如何检查对象列表是否包含具有指定属性的对象

时间:2016-12-23 10:57:51

标签: c# .net linq list

我有一个重复对象列表:

package com.java.demo;

import java.awt.Dimension;
import java.awt.GridBagLayout;
import java.util.Date;

import javax.swing.JFrame;
import javax.swing.JLabel;

public class Test {

    public static void main(String[] args) {
        JFrame frame = new JFrame("Test Frame");
        frame.setLayout(new GridBagLayout());

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setPreferredSize(new Dimension(250, 150));
        frame.setMaximumSize(new Dimension(250, 150));
        frame.setMinimumSize(new Dimension(250, 150));
        JLabel label = new JLabel(new Date().toString());
        frame.getContentPane().add(label);
        frame.setVisible(true);

    }

}

我想要一个var duplicates = workspace.Maps.GroupBy(m => m.sFolder).SelectMany(grp => grp.Skip(1)).ToList(); 语句来检查列表是否包含具有特定属性的对象:

if

有一种简单的方法吗?

4 个答案:

答案 0 :(得分:4)

你可以通过这种方式检查

if (duplicates.Any(a => a.sFolder == myObject.sFolder))
{
    // Do stuff
}

答案 1 :(得分:1)

不确定这里有什么比较,但这样的事情呢?

if (duplicates.Any(x => x.sFolder == myObject.sFolder)) 
{
    // Do stuff
}

答案 2 :(得分:1)

如果您需要重复对象进行进一步检查,请尝试

var duplicate = duplicates.FirstOrDefault(m => m.sFolder == myObject.sFolder);

if(duplicate != null)
{
    // Further check duplicate
}

答案 3 :(得分:0)

您可以使用public JsonResult programGrid(string sidx, string sord, int page, int rows) { programModel.id = "001"; programModel.ProgramDesc = "A"; programModel.InActive = true; programModel.UnitID = "Unit1"; programModelList.Add(programModel); programModel = new ProgramModel(); programModel.id = "002"; programModel.ProgramDesc = "B"; programModel.InActive = true; programModel.UnitID = "Unit1"; programModelList.Add(programModel); int pageIndex = Convert.ToInt32(page) - 1; int pageSize = rows; var results = programModelList.Select(emp => new { emp.id, emp.InActive, emp.ProgramDesc, emp.UnitID, }); int totalRecords = results.Count(); var totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows); if (sord.ToUpper() == "DESC") { results = results.OrderByDescending(s => s.id); results = results.Skip(pageIndex * pageSize).Take(pageSize); } else { results = results.OrderBy(s => s.id); results = results.Skip(pageIndex * pageSize).Take(pageSize); } var jsonData = new { total = totalPages, page, records = totalRecords, rows = results }; return Json(jsonData, JsonRequestBehavior.AllowGet);

foreach