GVKun编程网logo

c# – 在列表中的属性上使用.Contains()(c#列表定义)

15

在本文中,我们将详细介绍c#–在列表中的属性上使用.Contains()的各个方面,并为您提供关于c#列表定义的相关解答,同时,我们也将为您带来关于.net大数据量,查找Where优化(List的Co

在本文中,我们将详细介绍c# – 在列表中的属性上使用.Contains()的各个方面,并为您提供关于c#列表定义的相关解答,同时,我们也将为您带来关于.net 大数据量,查找 Where 优化(List 的 Contains 与 Dictionary 的 ContainsKey 的比较)、1.2.4 List.contains方法——判断列表中是否包含指定元素、63.Python中contains和icontains、angular – 无法使用ViewContainerRef读取未定义的属性“createComponent”的有用知识。

本文目录一览:

c# – 在列表中的属性上使用.Contains()(c#列表定义)

c# – 在列表中的属性上使用.Contains()(c#列表定义)

我有一份活动清单.在Activity类中是一个ID属性(参数的Guid).我想检查一下这个列表中是否有一个带有Guid的Activity.而不是这个:
foreach(Activity activity in ActivityList)
{
    if(activity.Id == GuidToCompare)
        //Code here
}

如果我只有一个Guids列表(而不是Activity列表)并使用.Contains(),是否有更有效的方法来实现相同的结果?

我有一个名为ActivityAndPO的结构列表.在这个结构中是一个Guid.
我有一份PO列表.在PO类中是Guid.

我想遍历ActivityAndPO列表中的所有对象,其中Guid存在于PO列表中.

解决方法

当然.
foreach(Activity activity in ActivityList.Where(a => a.Id == GuidToCompare) )
{        
    //Code here
}

但由于Id意味着最多只有1项活动:

//var act = ActivityList.Where(a => a.Id == GuidToCompare).SingleOrDefault(); // clearer
var act = ActivityList.SingleOrDefault(a => a.Id == GuidToCompare);          // shorter
if (act != null)
{
    //Code here
}

.net 大数据量,查找 Where 优化(List 的 Contains 与 Dictionary 的 ContainsKey 的比较)

.net 大数据量,查找 Where 优化(List 的 Contains 与 Dictionary 的 ContainsKey 的比较)

 最近优化一个 where 查询条件,查询时间很慢,改为用 Dictionary 就很快了。

 

 一、样例

 

假设:listPicsTemp 有 100w 条数据,pictures 有 1000w 条数据。

 

使用第 1 段代码执行超过 2 分钟。

var listPicsTemp = new List<string>();

pictures = pictures.AsParallel().Where(d => listPicsTemp.Contains(d.Pic)).ToList();

 

使用第 2 段代码执行十几毫秒。

var listPicsTemp = new List<string>();

var dicPicsTemp = listPicsTemp.Where(d => d != null).Distinct().ToDictionary(d => d);//使用Dictionary类型,速度快很多

pictures = pictures.AsParallel().Where(d => dicPicsTemp.ContainsKey(d.Pic)).ToList();

 

二、为什么 Dictionary 这么快呢?查看了一下微软官方文档。

 

下面截图来源:https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.generic.dictionary-2?view=netframework-4.7.2

 

 

三、查看源码

 

List 的源码:https://referencesource.microsoft.com/#mscorlib/system/collections/generic/list.cs,cf7f4095e4de7646

List 的 Contains,是循环 for 查找的。

 

Dictionary 的源码: https://referencesource.microsoft.com/#mscorlib/system/collections/generic/dictionary.cs,bcd13bb775d408f1

Dictionary 的 ContainsKey,是通过 hash 查找的。

 

 

 四、小结:

1、Dictionary<TKey,TValue> 类实现为哈希表。ContainsKey () 内部是通过 Hash 查找实现的,查询的时间复杂度是 O (1)。所以,查询很快。(List 的 Contains 是通过 for 查找的)

2、Dictionary 不是线程安全的。(查看微软官方文档,确实能学到很多知识盲区。)

1.2.4 List.contains方法——判断列表中是否包含指定元素

1.2.4 List.contains方法——判断列表中是否包含指定元素

contains方法用于判断列表中是否包含指定元素。如果列表中包含指定元素,则返回true,否则返回false。

语法  contains(Object o)

o:要判断是否存在于列表中的元素。

list列表中存在"a"时返回 true

 

list列表中不存在"f"时返回 false

 

 您觉得本文章对您有帮助,那么可以选择打赏。
打赏多少,您高兴就行,谢谢您的支持! ~(@^_^@)~

                          微信                支付宝

63.Python中contains和icontains

63.Python中contains和icontains

1. contains: 进行大小写敏感的判断,某个字符串是否包含在指定的字段中,这个判断条件使用大小写敏感进行判断,因此在被翻译成“SQL”语句的时候,会使用“like binary”, 而“like binary”就是使用大小写敏感进行判断。

2. icontains: 进行大小写不敏感的判断,某个字符串是否包含在指定的字段中,这个判断条件使用大小写不敏感进行判断,因此在被翻译成“SQL”语句的时候,会使用“like”, 而“like”就是使用大小写不敏感进行判断。其中icontains前面的i指的就是ignore(忽略)。

具体实例,示例代码如下:
models.py文件中模型的定义,示例代码如下:
from django.db import models


class Article(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()

# 重写类的__str__(self)方法
    def __str__(self):
        return "<(Article: id: %s,title: %s, content: %s)>" % (self.id, self.title, self.content)

# 重新定义表的一些属性,注意:此处的类的名字一定要为Meta
    class Meta:
        db_table = ''article''
1. contains: views.py文件中视图函数的示例代码如下:
from django.http import HttpResponse
from .models import Article


def index(request):
# 注意:此处是使用filter(),只有使用filter()之后才能够在article(QuerySet)上调用query属性,查看django底层转化的sql语句。
	article = Article.objects.filter(title__contains=''hello'')
	print(article)
	print(article.query)
	return HttpResponse(''success !'')
在mysql数据库中article表的数据信息如下:

在这里插入图片描述

因为contains进行的是大小写敏感的查找,所以不能找到匹配的数据,则会返回QuerySet为空。并且我们可以看到执行我们的查找条件的时候,django底层翻译成的sql语句中的:WHERE article.title LIKE BINARY %hello%,这里的LIKE BINARY 就可以保证进行的查找为大小写敏感的查找,并且hello字符串的两边会有%(代表hello字符串前面可以含有别的字符,后面也可以含有别的字符),这就可以验证我们上面的解释。

在这里插入图片描述

2.icontains: views.py文件中视图函数示例代码如下:
from django.http import HttpResponse
from .models import Article


def index(request):
    # icontains进行查找title中包含“hello”的字符串
    article = Article.objects.filter(title__icontains=''hello'')
    print(article)
    print(article.query)
    return HttpResponse("success")
因为使用icontains采用的是大小写不敏感的的查找方式,所以会返回两条满足条件的QuerySet,并且重以下打印的结果中可以看出,我们的查询条件被翻译成了:WHERE article.title LIKE %hello%,这里的LIKE进行的查找就是大小写不敏感的查找。

在这里插入图片描述

总结:iexact和exact进行的是准确性的查找,只有完全匹配我们的值“hello”的时候,才能够被找到。而icontains和contains中的查询条件,在进行查找的时候,会被翻译成sql语句中包含“%hello%”,在这里%意味着,前面可以含有n个字符,后面也可以含有n个字符。只要数据中包含hello字符串,就满足条件。

angular – 无法使用ViewContainerRef读取未定义的属性“createComponent”

angular – 无法使用ViewContainerRef读取未定义的属性“createComponent”

我正在尝试使用@ViewChild向父级位置注入动态组件,但我收到错误:

Cannot read property ‘createComponent’ of undefined

在我试图注入的ReferenceTableComponent组件上我有

@Component({
selector: 'app-reference-table',templateUrl: './refTable.component.html',styleUrls: ['./refTable.component.scss']
})
export class ReferenceTableComponent implements OnInit {

observable: Observable<any>;

@ViewChild('selectorTarget',{read: ViewContainerRef}) selectorTarget;

// colors
@input() public datas: Array<string>;

public availableColors: Array<string>;

@input() public nextRow: Array<string>;

//tailles
@input() public headList: Array<string>;

public rows: Array<any> = [{}];

public rowIDs: Array<any> = [];

constructor(private _cr: ComponentFactoryResolver,private _viewContainerRef: ViewContainerRef) {

}
ngOnInit() {
    this.computeAvailableColors();
}

addRow() {
    console.log('this.availableColors 2: ',this.availableColors)
    this.rows.push({});
}

    computeAvailableColors() {
    this.availableColors = _.concat([''],this.datas);
    this.rowIDs  = _.map(this.rows,'color')
    this.availableColors = _.difference(this.availableColors,this.rowIDs);
    const select: ComponentRef<SelectOptionsComponent> =
        this.selectorTarget.createComponent(
            this._cr.resolveComponentFactory(SelectOptionsComponent)
        );

    select.instance.availableColors = this.availableColors;
    select.instance.row = this.rows[0];
}

在我的组件html上

<td onSelectColor($event) #selectorTarget>
            </td>

我试图注入的组件

@Component({
selector: 'kia-select-options',template: `<div><select [(ngModel)]="row.color" (ngModelChange)="sendColorEvent(row,$event)"> 
                // value is a string or number
                <option *ngFor="let obj of availableColors">{{obj}}</option>
           </select></div>`
})
export class SelectOptionsComponent {

// couleurs
@input() public availableColors: Array<string>;

@input() public row: {};

public color: string;

@Output()
public changed = new EventEmitter();

constructor(private injector: Injector) {
}

sendColorEvent(row,color) {
    console.log(event)
    this.changed.emit({ color: color,row: row });
}
}

知道ReferenceTableComponent它是从父组件使用动态地自我填充,并且它工作正常

@ViewChild('target',{read: ViewContainerRef}) target;
  const factory = this.componentFactoryResolver.resolveComponentFactory(ReferenceTableComponent);
  const ref = this.target.createComponent(factory);

解决方法

@ViewChild()查询在ngOnInit()中不可用.仅在调用ngAfterViewInit()时:

ngAfterViewInit() {
    this.computeAvailableColors();
}

关于c# – 在列表中的属性上使用.Contains()c#列表定义的介绍现已完结,谢谢您的耐心阅读,如果想了解更多关于.net 大数据量,查找 Where 优化(List 的 Contains 与 Dictionary 的 ContainsKey 的比较)、1.2.4 List.contains方法——判断列表中是否包含指定元素、63.Python中contains和icontains、angular – 无法使用ViewContainerRef读取未定义的属性“createComponent”的相关知识,请在本站寻找。

本文标签: